Search code examples
androidandroid-databindingandroid-architecture-componentsmutablelivedataandroid-livedata

Using LiveData in data binding instead of MutableLiveData


Hi I am using LiveData instead of MutableLiveData because I am getting LiveData from Room and it is working even after removing binding.setLifecycleOwner(this);. My question, is there any problem with that? Hope it helps to others


Solution

  • If you're not going to set a LifecycleOwner, then you might as well not use LiveData.

    One of the biggest benefits of using LiveData, especially with Room and DataBinding is the ability for it to be lifecycle aware and have the values observed. Which means it'll be able to automatically update your Views with the latest updated data.

    According to official documentations: setLifecycleOwner() is used for a LiveData to be able to observe changes, such as from Room. If there's no LifecycleOwner set, then the LiveData won't be observed and no updates will be sent to your UI through Databinding.

    For a quick test, I've commented out the binding.setLifecycleOwner(this) in one of my Activities. The results proved the documentations are true. My UI was no longer getting changes from my LiveData objects.