我正在使用MutableLiveData存储用户做出的选择。该值是从另一个活动设置的。所以onResume我正在打电话
myMutableLivedata.value = newvale
但是,除非我调用invalidateall(),否则这不会更新UI。
这是MutableLiveData的预期行为
答案 0 :(得分:6)
对于LiveData
,您需要Observe
进行更改。
首先,创建您的MediatorLiveData
。
val liveData = MediatorLiveData<MyItem>()
接下来,在“活动/片段/等”中,您需要调用.observe
。触发Observer
时,它将具有更新的数据。
liveData.observe(this, Observer {
// Update the UI when the data has changed
})
最后,您可以在代码中的其他位置更新LiveData
的值,然后会通知Observer
。
// Somewhere else
liveData.value = MyItem("new value")