Data Binding with LiveData in Android
Prerequisite:
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.
Implementation
We need to declare the data in ViewModel as LiveData, We can use MutableLiveData ( most commonly ) it is just a class that extends LiveData.
Kotlin
class MainViewModel : ViewModel() { var text = MutableLiveData( " Welcome to my application " ) fun updateText() { text.value = " Text is updated successfully " } } |
- 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.
Kotlin
class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding lateinit var mainViewModel: MainViewModel override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) binding = DataBindingUtil.setContentView( this , R.layout.activity_main) // Creating MainViewModel object mainViewModel = MainViewModel() // Binding mainViewModel variable // with MainViewModel object binding.mainViewModel = mainViewModel // passing LifeCycleOwner to binding object binding.lifecycleOwner = this } } |
Output:
Text view is initialized with some text.
After clicking the UPDATE TEXT button.
Conclusion
- 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.
Please Login to comment...