什么时候使用 Android 的 LiveData 和 Observable 字段?

When to use Android’s LiveData and Observable field?

我正在实施 MVVM 和数据绑定,我想了解什么时候应该在 LiveData 上使用 Observable 字段?

我已经 运行 通过不同的文档发现 LiveData 是生命周期感知的,但在 Github 的示例代码中,这两个在 ViewModel 中同时使用。所以,如果 LiveData 比 Observable 字段更好,我很困惑,为什么不直接使用 LiveData?

可以一直用LiveData,只要有一个LifecycleOwner可以观察。我更喜欢将仅与 ViewModel 相关的绑定字段保留为 Observable,并将 LiveData 用于状态更改也与 Activity 或 [=16= 相关的字段].

两者都有各自的用例,例如:

  • 如果您想要为您的 UI 状态模型提供一个生命周期容错容器,LiveData 就是答案。

  • 如果你想让 UI 在视图模型中的某个逻辑发生更改时自行更新,请使用 ObservableFields.

我自己更喜欢使用 LivaDataObservableField/BaseObservable 的组合,LiveData 通常会充当生命周期感知数据容器,同时也是 VM 和虚拟机之间的通道查看。

另一方面,通过 LiveData 发出的 UI 状态模型对象本身是 BaseObservable 或者它们的字段是 ObservableField.

这样我就可以使用 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)
        }
}

ViewModel

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 状态模型。

编辑:现在成熟的我更喜欢Immutability而不是答案中解释的可变属性。

LiveData - 与 LifecycleOwner 一起使用,例如 activity 或 fragment

Observable - 与数据绑定一起使用