Android 何时使用安卓&x2019;s LiveData和可观察字段?
我正在实现一个MVVM和数据绑定,我试图理解什么时候应该在LiveData上使用Observable字段Android 何时使用安卓&x2019;s LiveData和可观察字段?,android,mvvm,android-databinding,android-livedata,Android,Mvvm,Android Databinding,Android Livedata,我正在实现一个MVVM和数据绑定,我试图理解什么时候应该在LiveData上使用Observable字段 我已经浏览了不同的文档,发现LiveData具有生命周期意识,但在Github的示例代码中,这两种数据同时在ViewModel中使用。所以,如果LiveData比Observable field好,我很困惑,为什么不直接使用LiveData呢?你可以一直使用LiveData,只要有LifecycleOwner可以观察。我更喜欢将仅与ViewModel相关的字段绑定为可观察的,并将LiveDa
我已经浏览了不同的文档,发现LiveData具有生命周期意识,但在Github的示例代码中,这两种数据同时在ViewModel中使用。所以,如果LiveData比Observable field好,我很困惑,为什么不直接使用LiveData呢?你可以一直使用
LiveData
,只要有LifecycleOwner
可以观察。我更喜欢将仅与ViewModel
相关的字段绑定为可观察的
,并将LiveData
用于状态更改也与活动相关的字段
或片段
都有各自的用例,例如:
- 如果您想要为UI状态模型提供一个生命周期容错容器,
就是答案LiveData
- 如果要在视图模型中的某个逻辑发生更改时使UI自身更新,请使用
observefields
LivaData
和observefield/baseobserveable
的组合,LiveData
通常作为生命周期感知的数据容器,也是VM和视图之间的通道
另一方面,通过LiveData
发出的UI状态模型对象本身是BaseObservable
或其字段为observableefield
这样,我就可以使用LiveData
对UI状态进行总体更改。
并在需要更新UI的一小部分时,将值设置到UI状态模型ObservableField
字段
编辑:
下面是有关UserProfile组件的快速说明,例如:
UIStateModel
data class ProfileUIModel(
private val _name: String,
private val _age: Int
): BaseObservable() {
var name: String
@Bindable get() = _name
set(value) {
_name = value
notifyPropertyChanged(BR.name)
}
var age: Int
@Bindable get() = _age
set(value) {
_age = value
notifyPropertyChanged(BR.age)
}
}
class UserProfileViewModel: ViewModel() {
val profileLiveData: MutableLiveData = MutableLiveData()
...
// When you need to rebind the whole profile UI object.
profileLiveData.setValue(profileUIModel)
...
// When you need to update a specific part of the UI.
// This will trigger the notifyPropertyChanged method on the bindable field "age" and hence notify the UI elements that are observing it to update.
profileLiveData.getValue().age = 20
}
视图模型
data class ProfileUIModel(
private val _name: String,
private val _age: Int
): BaseObservable() {
var name: String
@Bindable get() = _name
set(value) {
_name = value
notifyPropertyChanged(BR.name)
}
var age: Int
@Bindable get() = _age
set(value) {
_age = value
notifyPropertyChanged(BR.age)
}
}
class UserProfileViewModel: ViewModel() {
val profileLiveData: MutableLiveData = MutableLiveData()
...
// When you need to rebind the whole profile UI object.
profileLiveData.setValue(profileUIModel)
...
// When you need to update a specific part of the UI.
// This will trigger the notifyPropertyChanged method on the bindable field "age" and hence notify the UI elements that are observing it to update.
profileLiveData.getValue().age = 20
}
查看
您将观察到概要文件LiveData的正常更改
XML
您将使用数据绑定来绑定UI状态模型
编辑:现在,成熟的me更喜欢拥有答案中解释的可变属性。LiveData-与LifecycleOwner类活动或片段一起使用
Observable-与数据绑定一起使用您还可以展示一个小示例,说明您喜欢如何同时使用
LiveData
和BaseObserver
?添加了一个示例。谢谢!这是一个很好的例子解释。因此,LiveData就像可观察字段,可用于数据绑定和生命周期感知?是的,您可以直接在xml中使用LiveData进行数据绑定,如图所示。我自己更喜欢在代码中观察ViewModel中的LiveData,并将其值用作数据绑定模型,选择最适合您的:)