Data Binding with LiveData in Android
So, Why we are using Data binding with LiveData? Actually, If we want our views to directly communicate with ViewModel (Data source), we can do that simply without using LiveData. But if data changes in ViewModel it won’t reflect its View. This is where we can take the help of LiveData, to automatically update the view whenever there is any change in data.
We need to declare the data in ViewModel as LiveData, We can use MutableLiveData ( most commonly ) it is just a class that extends LiveData.
- We can use a method value() to update the data (it must be called from the main thread if you are calling from the background thread you need to use postValue( ) method ).
- Normally we use observer( ) to binds the view and LiveData, but here as we are using Data Binding in which we have directly bind the views with data we don’t need an observer( ).
- One thing to note is that as we need to give LifeCycleOwner to LiveData we were passing the LifeCycleOwner to observer( ).
- But Here we can also pass the LifeCycleOwner to Binding object using lifecycleOwner( ) method.
Text view is initialized with some text.
After clicking the UPDATE TEXT button.
- As we can see that when the app is open the Text View is set by default.
- And when we click the UPDATE TEXT button the Text View is updated.
- So our application is ready and working properly.
- We have implemented Data Binding using ViewModel and LiveData.