Android Data Binding Library — from Observable Fields to LiveData in two steps

Jose Alcérreca
Android Developers
Published in
2 min readMar 25, 2019

--

Illustration by Virginia Poltrack

One of the most important features of Data Binding is observability. It allows you to bind data and UI elements so that when the data changes, the pertinent elements are updated on screen.

Plain primitives and Strings are not observable by default so if you use them in your Data Binding layouts, their values will be used when the binding is created but subsequent changes to them will be ignored.

To make objects observable, we included in the Data Binding Library a series of observable classes: ObservableBoolean , ObservableInt, ObservableDouble… and the generic , ObservableField<T>. We’ll call these Observable Fields from now on.

Some years later, as part of the first wave of Architecture Components, we released LiveData, which is another observable. It was an obvious candidate to be compatible with Data Binding, so we added this capability.

LiveData is lifecycle-aware but this is not a huge advantage with respect to Observable Fields because Data Binding already checks when the view is active. However, LiveData supports Transformations, and many Architecture Components, like Room and WorkManager, support LiveData.

For these reasons, it’s recommended to migrate to LiveData. You only need two simple steps to do so.

Step 1: Replace Observable Fields with LiveData

If you are using Observable Fields directly in your data binding layout, simply replace ObservableSomething (or ObservableField<Something>) with LiveData<Something>.

Before:

Remember that %lt; is not a typo. You have to escape the < character inside XML layouts.

After:

Alternatively, if you’re exposing observables from a ViewModel (the preferred approach) or a presenter or controller, you don’t need to change your layout. Just replace those ObservableFields with LiveData in the ViewModel.

Before:

After:

Step 2 — Set the lifecycle owner for the LiveData

Binding classes have a method called setLifecycleOwner that must be called when observing LiveData from a data binding layout.

Before:

After:

Note: If you’re setting the content for a fragment, it is recommended to use fragment.viewLifecycleOwner (instead of the fragment’s lifecycle) to deal with potential detached fragments.

Now you can use your LiveData objects with Transformations and MediatorLiveData. If you’re not familiar with these features, check out this recording of “Fun with LiveData”, from the Android Dev Summit 2018.

--

--

Jose Alcérreca
Android Developers

Developer Relations Engineer @ Google, working on Android