Search code examples
androidkotlinmutablelivedata

android : mutablelivedata change is not updating the UI


I am using MutableLiveData to store a choice user has made. The value is set from another activity. SO onResume i am calling

 myMutableLivedata.value = newvale

But this does not update the UI unless i call a invalidateall().

Is this expected behaviour of MutableLiveData


Solution

  • For LiveData, you need to Observe the changes.

    First, create your MediatorLiveData.

    val liveData = MediatorLiveData<MyItem>()
    

    Next, within your Activity/Fragment/Etc, you need to call .observe. When the Observer is fired, it will have the updated data.

    liveData.observe(this, Observer { 
        // Update the UI when the data has changed
    })
    

    And lastly, somewhere else in code, you can update the value of your LiveData, and the Observer will be notified.

    // Somewhere else
    liveData.value = MyItem("new value")