android:mutablelivedata更改不更新UI

png*_*png 3 android kotlin mutablelivedata

我正在使用MutableLiveData来存储用户所做的选择.该值是从另一个活动设置的.SO onResume我正在打电话

 myMutableLivedata.value = newvale
Run Code Online (Sandbox Code Playgroud)

但是除非我调用invalidateall(),否则这不会更新UI.

这是MutableLiveData的预期行为

Adv*_*Dog 6

对于LiveData,您需要进行Observe更改.

首先,创建你的MediatorLiveData.

val liveData = MediatorLiveData<MyItem>()
Run Code Online (Sandbox Code Playgroud)

接下来,在您的Activity/Fragment/Etc中,您需要调用.observe.当Observer被触发,这将有更新的数据.

liveData.observe(this, Observer { 
    // Update the UI when the data has changed
})
Run Code Online (Sandbox Code Playgroud)

最后,在代码中的其他位置,您可以更新您的值LiveData,并将Observer通知.

// Somewhere else
liveData.value = MyItem("new value")
Run Code Online (Sandbox Code Playgroud)