png
png

Reputation: 4408

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

Upvotes: 4

Views: 4474

Answers (1)

advice
advice

Reputation: 5988

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")

Upvotes: 8

Related Questions