Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Data Binding with LiveData in Android

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article


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.


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.


class MainActivity : AppCompatActivity() {
    lateinit var binding: ActivityMainBinding
    lateinit var mainViewModel: MainViewModel
    override fun onCreate(savedInstanceState: Bundle?) {
        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 


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.

My Personal Notes arrow_drop_up
Last Updated : 07 Oct, 2021
Like Article
Save Article
Similar Reads