◾︎简介
LiveData 是一种可观察的数据存储器类。与常规的可观察类不同,LiveData 具有生命周期感知能力,意指它遵循其他应用组件(如 Activity、Fragment 或 Service)的生命周期。这种感知能力可确保 LiveData 仅更新处于活跃生命周期状态的应用组件观察者。
这是官网上的一段话。意思就是 LiveData 的更新能够被 LifecycleOwner 所感知,但是前提是 LifecycleOwner 处于活跃状态。这样就有效的避免了更新 UI 时 Activity 已经不处于活跃而导致的崩溃。
本文代码使用 Kotlin 讲解,若需查看 Java 代码写法,请参考文末 Sample
◾︎添加依赖
LiveData 一般和 ViewModel 一起使用。
def lifecycle_version = "2.3.1"
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
◾︎使用
应当避免将 LiveData 直接存储在 Activity / Fragment 中,因为 Activity / Fragment 只负责 UI 显示,而不负责数据存储。
简单的使用 LiveData
- 在 ViewModel 中定义 LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class NameViewModel : ViewModel() {
val currentName: MutableLiveData<String> by lazy {
MutableLiveData<String>()
}
}
- 使用 LiveData 的 observe 方法
import androidx.lifecycle.ViewModelProvider
viewModel = ViewModelProvider(this)[NameViewModel::class.java]
viewModel?.currentName?.observe(this, {
name -> textView.text = name })
observe 方法有两个参数
- 第一个是 LifecycleOwner 对象。这样 LiveData 就会感知 LifecycleOwner 的生命周期,只在 LifecycleOwner 活跃的时候才去调用第二个参数的 onChanged 方法
- 第二个参数是 Observer 对象。Observer 是一个 interface,它的 onChanged 会在 LiveData 更新的时候被调用
- 更新 LiveData
viewModel?.<