1). 简介
LiveData是一个可观察的数据持有者类。 与常规observable不同,LiveData是生命周期感知的,这意味着它尊重其他应用程序组件的生命周期,例如活动,片段或服务。 此感知确保LiveData仅更新处于活动生命周期状态的应用程序组件观察者。
2). 依赖
官方依赖
dependencies {
def lifecycle_version = "1.1.1"
// ViewModel and LiveData
implementation "android.arch.lifecycle:extensions:$lifecycle_version"
// alternatively - just ViewModel
implementation "android.arch.lifecycle:viewmodel:$lifecycle_version" // use -ktx for Kotlin
// alternatively - just LiveData
implementation "android.arch.lifecycle:livedata:$lifecycle_version"
// alternatively - Lifecycles only (no ViewModel or LiveData).
// Support library depends on this lightweight import
implementation "android.arch.lifecycle:runtime:$lifecycle_version"
annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version" // use kapt for Kotlin
// alternately - if using Java8, use the following instead of compiler
implementation "android.arch.lifecycle:common-java8:$lifecycle_version"
// optional - ReactiveStreams support for LiveData
implementation "android.arch.lifecycle:reactivestreams:$lifecycle_version"
// optional - Test helpers for LiveData
testImplementation "android.arch.core:core-testing:$lifecycle_version"
}
此处在使用时,我没有添加依赖,Android Studio3.0 项目中已经默认依赖
3). 优点
- 确保UI符合数据状态
- 没有内存泄漏
- 活动停止不会崩溃
- 不需要手动处理声明周期
- 始终保持最新数据
- 适当的配置更改
- 共享资源
4). 创建LiveData
- NameViewModel
class NameViewModel : ViewModel() {
// Create LiveData Objects
var currentName : MutableLiveData<String>? = null
get() {
if (null == field) {
currentName = MutableLiveData()
}
return field
}
}
- LiveDataActivity
// 初始化ViewModel
model = ViewModelProvider.AndroidViewModelFactory.getInstance(application).create(NameViewModel::class.java)
// 创建观察者更新UI
val nameObserver = Observer<String> {
name: String? ->
tv_show.text = name
}
// 观察LiveData
model.currentName?.observe(this, nameObserver)
5). 修改
// 修改文本
btn_change.setOnClickListener {
val name = "John"
// 修改数据
model.currentName?.value = name
}
6). 转换LiveData
LiveData<User> userLiveData = ...;
LiveData<String> userName = Transformations.map(userLiveData, user -> {
user.name + " " + user.lastName
});