ObservableField 还是 LiveData?哪一个是最好的?

ObservableField or LiveData? Which one is the best?

我一直在测试 Livedata 和 AAC。

LiveData和ObservableField的核心区别是什么?

哪个最好,我什么时候应该使用一个而不是另一个?

核心区别在于 ObservableField<T> 不具备生命周期感知能力,因此无法进行任何自动订阅管理。虽然 LiveData<T> 具有生命周期感知能力,并且在 Activity/Fragment 生命周期方面解决了订阅管理方面的大量难题。

没有一种方法可以回答什么是最好的。这是个人选择,但我建议使用 LiveData<T> 只是为了节省时间并避免将来出现潜在问题。

LiveDataObservable可以交替使用。 LiveData 是生命周期感知的,因此只会通知 "active" 的可观察对象。

引用官方文档 https://developer.android.com/topic/libraries/data-binding/architecture#livedata

Unlike objects that implement Observable—such as observable fields—LiveData objects know about the lifecycle of the observers subscribed to the data changes. This knowledge enables many benefits, which are explained in The advantages of using LiveData. In Android Studio version 3.1 and higher, you can replace observable fields with LiveData objects in your data binding code.

如前所述,两者都可用于 UI 可互换绑定。 LiveData 是一种快速方法,但如果您想要对绑定进行更多控制,Obserable 是一种方法。

引用官方文档 https://developer.android.com/topic/libraries/data-binding/architecture#observable-viewmodel

There are situations where you might prefer to use a ViewModel component that implements the Observable interface over using LiveData objects, even if you lose the lifecycle management capabilities of LiveData. Using a ViewModel component that implements Observable gives you more control over the binding adapters in your app. For example, this pattern gives you more control over the notifications when data changes, it also allows you to specify a custom method to set the value of an attribute in two-way data binding.

我们可以选择在 Observable 的情况下自定义绑定,这在某些情况下可能会有帮助。

个人偏好LiveData。如果需要对绑定进行一些自定义或更多控制,请选择 Obervable

相似之处

  • 与数据绑定配合得很好
  • 绑定的视图在后台自动退订
  • POJO classes 也可以订阅更改

差异

  • LiveData 允许 POJO 订阅者了解生命周期。这意味着,如果您有一个 属性 B,您希望在 A 更改时更新,您可以选择在附加视图处于非活动状态时不接收更新。这样可以节省资源。
  • ObservableField<T> 的后台线程更新是即时的。 MutableLiveData.postData 延迟。
  • LiveData<T>ObservableField<T> 的值始终可以为 null,但原始实现 ObservableInt-Float-Boolean 等是 non-nullable .
  • MutableLiveData<T> 在初始化时不采用构造函数值来设置。

什么时候用什么

  • 您是否有外部事件可能会在应用程序处于后台时触发 ViewModel 中的级联数据更改?你应该选择 LiveData
  • 您是否需要在后台线程上立即更新值*?使用 Observables

None以上的要求?两者都不会出错,但 ObservableField 更简单 class.

*) “立即”是指 set/postValue 之后的 get 保证 return 您刚刚设置的值。 None 的类型当然是立即 UI 更新。