はじめに
LiveDataとかLifecycleOwnerとかよく聞くけどいまいちなんなのかが分からないので、めちゃくちゃふんわりまとめていきます。
理解が進み次第追記予定
LiveDataとは
- データを保持してくれる箱みたいなやつ
- LiveDataと言いつつ、大体MutableLiveDataかObservableFieldを使う
- MutableLiveData→必要な時のみ監視し、別途LifeCycleOwnerを設定する必要がある
- ObservableField→常に変更を監視し続ける
-
val count = MutableLiveData<Int>("0")
みたいな感じで使う
MutableLiveDataで必要になってくるLifecycleOwnerとは?
- 大体ActivityやFragmentをLifecycleOwnerに設定する
- ActivityやFragmentのライフサイクルに応じて変更を監視したりしなかったりする
- ActivityやFragmentがstopした時などは変更を監視する必要がないので効率がいい
- Activity/Fragmentにいる状態で
binding.lifecycleOwner = this
とかで設定する