본문 바로가기
안드로이드 코틀린

[Kotlin][Android] LiveData 사용 방법

by teamnova 2021. 8. 11.

오늘은 Android JetPack 중 하나인 LiveData에 대해 알아보도록 하겠습니다.

 

Live Data

라이브 데이터는 LifeCycle을 인식할 수 있는 관찰가능한 데이터 홀더 클래스입니다. 라이프 사이클을 인식할 수 있다는 것은 수명 주기를 고려한 다는 의미입니다. 

 

생명주기가 Started, Resume 상태이면 LiveData는 관찰자를 활성화 상태로 인식합니다. LifeCycle이 Destroyed가 되면 관찰자를 삭제할 수 있습니다.

 

https://developer.android.com/topic/libraries/architecture/livedata?hl=ko

 

LiveData 개요  |  Android 개발자  |  Android Developers

LiveData를 사용하여 수명 주기를 인식하는 방식으로 데이터를 처리합니다.

developer.android.com

Live Data 사용의 이점

 

1. UI 데이터 상태의 일치 보장

앱 데이터 및 라이프 사이클이 변경될 때 마다 observer을 통해 데이터를 변경할 수 있습니다.

 

 

2. 메모리 누출 없음

 

연결된 수명 주기가 끝나면 자동으로 삭제됩니다. 

 

 

3. 중지된 활동으로 인한 비정상 종료 없음

 

관찰자의 수명 주기가 비활성화 상태이면 관찰자는 어떤 Live Data 이벤트도 받지 않음.

 

 

4. 수명주기를 수동으로 처리하지 않음

 

수명 주기의 변경을 자동으로 인식함으로 수동으로 처리하지 않습니다. 

 

 

5. 최신 데이터 유지

 

수명 주기가 비활성화 일 경우 다시 활성화가 될 때 새로운 데이터를 받습니다. 

 

 

 

 

그럼 시작해볼까요?

 

먼저 build.gradle (module) 에서 plugin을 확인해줍니다. 

plugins {
   ...
    id 'kotlin-android-extensions'
   ... 
}

 

 

LiveData를 사용하기 위해서는 app의 build.gradle 파일에 androidx의 appcompat 종속성을 추가하기만 하면 사용준비가 완료됩니다. 

 

 

1. App수준의 build.gradle 종속성 확인

 

2. LiveData를 사용할 곳에서 LiveData 정의

 

private var liveText: MutableLiveData<String> = MutableLiveData()

LiveData는 abstract class이기 때문에 LiveData Class를 상속받은 MutableLiveData를 사용합니다.

 

 

3. LiveData에 Observer 달기

 

// LiveData의 value의 변경을 감지하고 호출
liveText.observe(this, Observer {
    // it로 넘어오는 param은 LiveData의 value
})

- 첫 번째 매개변수인 this는 LifeCycleOwner인 MainActivity 입니다.

- 두 번째 매개변수인 Observer Callback은 LiveData(liveText)의 value의 변경을 감지하고 호출되는 부분입니다.

 

 

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/btn_change"
        app:layout_constraintVertical_chainStyle="packed"/>

    <Button
        android:id="@+id/btn_change"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ADD 1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/text_test"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

 

MainActivity.kt

package com.example.stickodelivedata

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private var liveText: MutableLiveData<String> = MutableLiveData()
    private var count = 0 // button을 누르면 증가 될 숫자

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // LiveData의 value의 변경을 감지하고 호출
        liveText.observe(this, Observer {
            // it로 넘어오는 param은 LiveData의 value
            text_test.text = it
        })

        btn_change.setOnClickListener {
            // liveText의 value를 변경
            // liveText 자체를 변경시키면 안됨
            liveText.value = "Hello World! ${++count}"
        }
    }
}