LiveData vs. ObservableField for data binding

Viewed 4233

There are multiple questions on Stackoverflow related to difference between LiveData and ObservableField. Also, I have found multiple articles on the internet about this topic. All of them explain that LiveData is lifecycle-aware unlike ObservableField. Most of them also mention that it is advantageous to use LiveData instead of ObservableField if component such as Activity or Fragment observe the attribute, so we don't need to unsubscribe.

However, even after reading all of that, what is still not clear to me is if there is or isn't some advantage of using LiveData over ObservableField for data binding. For example:

ViewModel:

class UserViewModel(user: User) : ViewModel {
    val userName = ObservableField<String>(user.name) // Option 1
    val userName = MutableLiveData<String>(user.name) // Option 2
}

Layout:

<layout>
    <data>
        <variable name="viewModel" type="com.example.UserViewModel" />
    </data>
    ...
</layout>

For option 2, I will also have to use binding.setLifecycleOwner(activity), of course. Let's assume that nothing else than the layout observes userName.

My questions is:

Is there any advantage of using option 2 over option 1 or it doesn't matter in this case since the view (layout) will simply observe until it exists ?

What confuses me even more is this article: https://android.jlelse.eu/android-architecture-components-livedata-with-data-binding-7bf85871bbd8 which says: "In the previous approach (without LiveData) if we wanted to show the data on the UI, we should previously check if it still exists. With LiveData we don’t need to worry about it because data will be posted only if Activity is at least started (so in started or resumed state)."

I don't understand this quoted part. What is meant by checking if UI still exists in case of "previous approach" which uses ObservableField? How would you apply this check for my example in option 1 ?

1 Answers

When you use the ObservableField and you listen to its changes then you get notified in both cases:

  1. When activity is visible to a user.
  2. When activity is not visible (in the paused or destroying state).

now when u get notified for such event and you need to change UI like textView etc case 1 will work fine as the activity is visible but in case 2 it is not suggested to change UI as the activity is not visible and also it may crash if view does not exist(Like state of finishing the activity).

so Here to avoid this case 2 crashes and unwanted data changes Live data comes to play as in Live data you will get change events only if an activity is visible. Live data observers works according to the lifecycle of Activity/Fragment. So you don't need to check if view exists before UI update as the observer it itself not called.

Related