안드로이드 프로그래밍[Kotiln Code]/Database(Room, Realm, Live Data )

[Live Data] 안드로이드 라이브 데이터 1

훈츠 2020. 4. 2. 02:03
반응형

안녕하세요. 훈츠 입니다. Room Database 와 Realm Database 학습 하면서 라이브 데이터 관련하게 나와서 학습 하는김에 정리 해봅니다. 

라이브 데이터 사용시 키 포인트 

  • View Model 안에서 다음과 같이 구성 
    • Live Data get() = Mutable Live Data
  • Activity 혹은 Fragment 안에서 viewModel 가져오고 observer할 view 지정
    • viewModel.LiveData.observe (this , Observer { Change UI } ) 

뷰모델 안에  라이브 데이터 생성 

on Create() Observer 에서 UI 연결 

다른 곳에서 라이브데이터 변경시

LiveData 개요

LiveData는 식별 가능한 데이터 홀더 클래스입니다. 식별 가능한 일반 클래스와 달리 LiveData는 수명 주기를 인식합니다. 즉 활동, 프래그먼트 또는 서비스와 같은 다른 앱 구성요소의 수명 주기를 고려합니다. 이러한 수명 주기 인식을 통해 LiveData는 활성 수명 주기 상태에 있는 앱 구성요소 관찰자만 업데이트합니다.

라이브 데이터 뿐만 아니라, AndroidX 에 배포 노트를 확인 하시면 최신 버젼 부터 history를 알수 있습니다. 

https://developer.android.com/jetpack/androidx/releases/lifecycle?hl=en

 

Lifecycle  |  Android 개발자  |  Android Developers

수명 주기 인식 구성요소는 활동 및 프래그먼트와 같은 다른 구성요소의 수명 주기 상태 변경에 따라 작업을 실행합니다. 이러한 구성요소를 사용하면 잘 구성된 경량의 코드를 만들어 더욱 쉽게 유지할 수 있습니다. 자세한 내용은 참조 문서에서 확인하세요. 최근 업데이트 현재 안정화 버전 다음 출시 후보 베타 버전 알파 버전 2020년 1월 22일 2.2.0 - - - 종속성 선언 Lifecycle의 종속성을 추가하려면 프로젝트에 Google Maven 저장소를

developer.android.com

 

현재 최신 버전

apply plugin: 'kotlin-android'

dependencies {
        def lifecycle_version = "2.2.0"
        def arch_version = "2.1.0"

        // ViewModel
        implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
        // LiveData
        implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
        // Lifecycles only (without ViewModel or LiveData)
        implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"

        // Saved state module for ViewModel
        implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"

        // Annotation processor
        kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
        // alternately - if using Java8, use the following instead of lifecycle-compiler
        implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"

        // optional - ReactiveStreams support for LiveData
        implementation "androidx.lifecycle:lifecycle-reactivestreams-ktx:$lifecycle_version"

        // optional - Test helpers for LiveData
        testImplementation "androidx.arch.core:core-testing:$arch_version"
    }

구글 developers 

LiveData는 Observer 클래스로 표현되는 관찰자의 수명 주기가 STARTED 또는 RESUMED 상태에 있으면 관찰자가 활성 상태에 있는 것으로 간주합니다. LiveData는 활성 관찰자에게만 업데이트 정보를 알립니다. LiveData 개체를 관찰하도록 등록된 비활성 관찰자에게는 변경 관련 알림이 전달되지 않습니다.

LifecycleOwner 인터페이스를 구현하는 개체와 쌍을 이루는 관찰자를 등록할 수 있습니다. 이 관계를 통해 Lifecycle 개체의 상태가 DESTROYED로 변경될 때 관찰자를 삭제할 수 있습니다. 이는 활동 및 프래그먼트에 특히 유용합니다. 활동 및 프래그먼트가 LiveData 개체를 안전하게 관찰할 수 있으며, 수명 주기가 끝나는 즉시 활동 및 프래그먼트의 구독이 취소되어 누출을 걱정할 필요가 없기 때문입니다.

LiveData 사용의 이점

  • UI와 데이터 상태의 일치 보장
  • 메모리 누출 없음
  • 중지된 활동으로 인한 비정상 종료 없음
  • 수명 주기를 더이상 수동으로 처리할 필요 없음
  • 항상 최신 데이터 유지 

리소스 공유 

싱글톤 패턴을 사용하는 LiveData 개체를 확장하여 시스템 서비스를 앱에서 공유하도록 래핑할 수 있습니다. LiveData 개체가 시스템 서비스에 한 번 연결되면 리소스가 필요한 모든 관찰자는 LiveData 개체를 바로 관찰할 수 있습니다. 자세한 내용은 LiveData 확장을 참조하세요

LiveData 개체 사용

  1. ViewModel 클래스 내 LiveData 인스턴스 만들기. (다른곳도 가능)
    •  LiveData get() = MutableLiveData : 이렇게 연결 
  2. onChanged() 메서드를 정의하는 Observer 개체 만들기 
    • 이 onChanged() 메서드는 LiveData 개체에서 보유한 데이터가 변경될때 발생하는 작업을 제어 합니다. 일반적으로 활동 또는 프래그먼트와 같은 UI 컨트롤러에 Observer 개체를 만듭니다.
  3. observe() 메서드를 사용하여 Observer 개체를 LiveData 개체에 연결하기 
    • observe() 메서드는 LifecyclerOwner 개체를 가져옵니다. 이렇게 하면 Observer개체가 LiveData 개체를 구독함으로써 변경 알림을 받을수 있습니다. 일반적으로 활동 또는 프래그먼트와 같은 UI 컨트롤러에서 Observer 개체를 연결 합니다. 
참고:
observeForever(Observer) 메서드를 사용하면 연결된 LifecycleOwner 개체 없이 관찰자를 등록할 수 있습니다. 이 경우 관찰자는 항상 활성 상태로 간주되므로 항상 수정 관련 알림을 받습니다. removeObserver(Observer) 메서드를 호출하여 이러한 관찰자를 삭제할 수 있습니다.
class MainViewModel :ViewModel(){

    // 1. LiveData 인스턴스 만들기
    // 처음 LiveData 개체에 데이터가 설정 되어 있지 않습니다.
    val currentName :MutableLiveData<String> by lazy {
        MutableLiveData<String>()
    }

}
class MainActivity : AppCompatActivity() {

    private lateinit var model: MainViewModel
    lateinit var viewModelFactory : ViewModelProvider.AndroidViewModelFactory
    val nameList = listOf<String>("lee","kim","shin")
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // Get the ViewModel
        viewModelFactory = ViewModelProvider.AndroidViewModelFactory.getInstance(application)
        model = ViewModelProvider(this, viewModelFactory).get(MainViewModel::class.java)

        // Create the Observer which updates the UI
        val nameObserver = Observer<String> {
            nameTextView.text = it
        }
        // Observe the LiveData, passing in this activity as the LifeCycleOwner and the observer.
        model.currentName.observe(this, nameObserver)

        //
        button.setOnClickListener{
            model.currentName.value = nameList.random()
        }
        btManu2.setOnClickListener{
            val intent = Intent(this, Main2Activity::class.java)
            startActivityForResult(intent,100)
        }

    }
}



Live Data 실습 Code with FakeRepository

https://github.com/rain2002kr/DataBindingAndLiveData.git

 

rain2002kr/DataBindingAndLiveData

Contribute to rain2002kr/DataBindingAndLiveData development by creating an account on GitHub.

github.com

 

반응형