与常规的可观察类不同,LiveData 具有生命周期感知能力,意指它遵循其他应用组件(如 Activity、Fragment 或 Service)的生命周期。这种感知能力可确保 LiveData 仅更新处于活跃生命周期状态的应用组件观察者。
LiveData 只会将更新通知给活跃的观察者。为观察 LiveData 对象而注册的非活跃观察者不会收到更改通知。
使用 LiveData 的优势
- 确保界面符合数据状态
- 不会发生内存泄露
- 不会因为Activity停止导致崩溃
- 不需要手动处理生命周期
- 数据始终最新
将LiveData组件导入项目
def lifecycle_version = "2.2.0"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
使用步骤
创建LiveData对象
LiveData对象通常存储在ViewModel对象中
class NameViewModel : ViewModel() {
val currentName: MutableLiveData<String> by lazy {
MutableLiveData<String>()
}
}
在Activity的onCreate中观察LiveData对象
如果LiveData中有值,在绑定观察者时会立即调用一次onChanged方法,从而将LiveData中最新的值输出
model = ViewModelProvider(this).get(NameViewModel::class.java)
val nameObserver = Observer<String> {
binding.tv1.text = it
}
model.currentName.observe(this, nameObserver)
更新LiveData对象内容
binding.btn1.setOnClickListener {
model.currentName.postValue("update str")
model.currentName.value = "update str"
}
- postValue:如果当前线程不为主线程,会通过ArchTaskExecutor使得观察事件运行在主线程,效率较低,但不易出错
- setValue:观察事件运行在当前线程,如当前线程不为主线程,需要更新UI请注意
当前完整代码
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var cameraManager: CameraManager
private lateinit var model: NameViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btn1.text = "点击"//视图绑定示例
val user = User()//数据绑定示例
user.name = "before"
binding.user = user
cameraManager = CameraManager()//生命周期示例
lifecycle.addObserver(cameraManager!!)
//LiveData示例
model = ViewModelProvider(this).get(NameViewModel::class.java)
val nameObserver = Observer<String> {
binding.tv1.text = it
}
model.currentName.observe(this, nameObserver)
binding.btn1.setOnClickListener {
model.currentName.postValue("update str")
}
}
}
扩展LiveData
-
当 LiveData 对象具有活跃观察者时,会调用 onActive() 方法。这意味着,您需要从此方法开始观察股价更新。
-
当 LiveData 对象没有任何活跃观察者时,会调用 onInactive() 方法。由于没有观察者在监听,因此没有理由与 StockManager 服务保持连接。
-
setValue(T) 方法将更新 LiveData 实例的值,并将更改通知给任何活跃观察者。
-
如果 Lifecycle 对象未处于活跃状态,那么即使值发生更改,也不会调用观察者。
-
销毁 Lifecycle 对象后,会自动移除观察者。