Data Binding with ViewModel in Android
What is the benefit of integrating data binding in ViewModel? Simply we can say, It provides easy communication between VIEW and its data (or can say View’s Data). As we know the Views are defined in XML files and the XML file are linked with their activity or fragment file, but their data are stored in ViewModel objects. So if the data wants to communicate with the Views, the Activity or Fragment file will act as an intermediator. This will also increase the productivity of developers as it reduces boilerplate codes. So, In this article will we get to how to connect the Views and their Data directly which is there in ViewModel objects.
We will learn this by creating a simple app using Kotlin.
Create an app with an empty activity. As we are using Data binding we need to enable Data Binding in build.gradle file
Create a ViewModel class
Now we need to create a layout in XML and create a variable in the XML layout. Using data tag we declare a variable.
Now, we need to create a binding object in Activity, to pass the data to the variable which we defined in XML layout and MainViewModel object as a data source for the Views.
Our app is ready and it’s also working as we can see the data in form of text which was stored in the ViewModel object. So, we got to know how we directly communicate the View with its Data without taking the help of any intermediate. But, in this app, there is one issue as if we click the UPDATE TEXT button the text won’t be updated as expected, but it will remain the same. This is because we need to set the change text ( Data ) again to the View for any new data changes, so we need to define a function in the Activity file to Update the view. But we don’t want the communicate the View with Activity.
So here we can use Live Data, Simply we can say, Live data is observer data holder class. If we declare any data as LiveData, then the data can be observed by Android components like Activity, Fragments, etc. Therefore, if we declare any data as Live Data and bind it using view binding to a View, then whenever the data changes the View gets automatically gets updated. In this article, we have discussed only Data binding with ViewModel and in the next article, we will also see Data Binding with LiveData.
Please Login to comment...