I have been testing Livedata and AAC in general.
What is the core difference between LiveData and ObservableField?
Which one is the best and when should I use one over another?
ObservableField is not Lifecycle aware but LiveData is lifecycle aware and hence will notify only the observables which are “active”.
The advantages of using LiveData Using LiveData provides the following advantages: Ensures your UI matches your data state. LiveData follows the observer pattern. LiveData notifies Observer objects when underlying data changes.
MutableLiveData is commonly used since it provides the postValue() , setValue() methods publicly, something that LiveData class doesn't provide. LiveData/MutableLiveData is commonly used in updating data in a RecyclerView from a collection type(List, ArrayList etc).
Else, we can use callback or RxJava in ViewModel. Another compromise is implement MediatorLiveData (or Transformations) and observe (put your logic here) in ViewModel. Notice MediatorLiveData observer won't trigger (same as Transformations) unless it's observed in Activity/Fragment.
The core difference is that ObservableField<T>
is not lifecycle-aware and hence there cannot be any automatic subscription management. While LiveData<T>
is lifecycle-aware and solves tons of headaches with subscription management when it comes to Activity/Fragment
lifecycles.
There is no one way to answer what is the best to use. It is a personal choice, but I would suggest using LiveData<T>
just to save yourself some time and avoid potential issues in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With