Android Architecture Components meets Data Binding : Lifecycle awareness!

Finally Android Data Binding library got updated to play nice with Android Architecture Components library and became life-cycle aware! This means that any changes to the LiveData objects will be reflected in the layouts... automagically! :)
* Tested on Android Studio 3.1 - canary 6

Whats new?


To make the binding life-cycle aware you need to pass the life-cycle owner to the ViewDataBinding by calling the setLifecycleOwner method.

The ViewModel:

Our view model consists of the LiveData object that is simply and observable data container, where the observer gets notified of data changes.

The model:

Our model has one field that is used to store user's name. A POJO.

The layout:

-Out layout consists of a text field that is bound to the user's name. And will be updated when our LiveData container posts a change.
-We also have an EditText that is two-way bound to the user's name, meaning when text gets entered, the name is updated and vise-versa, when the user LiveDate is updated the EditText is updated.
-And finally a button onClick of which we post a change to our LiveData and all the observers get notified.

The result:



Resources:

  • Full source for the project: here




Comments

Post a Comment

Popular posts from this blog

Android Data Binding : Dynamic RecyclerView Adapter

Android Architecture Components : LiveData

Android Data Binding : Tricks and Magic