【发布时间】:2020-02-07 20:55:33
【问题描述】:
我在 MVVM 架构上使用多个 MutableLiveData。 在 ViewModel 上,我发布了对象,但片段没有恢复。 当片段恢复时,观察者得到 MutableLiveData 但不是按照我发布它们的顺序。 如何强制获取 MutableLiveData 的命令?
视图模型:
void foo(){
first_MutableLiveData.post(newData)
second_MutableLiveData.post(newData)
}
片段:
initView(){
first_MutableLiveData.observe(this,()->{
"getting called second"})
second_MutableLiveData.observe(this,()->{
"getting called first"})
}
【问题讨论】:
-
你在哪里注册观察片段?
-
在onViewCreated中
-
您的片段消息已切换。这是故意的吗?
-
消息是按目的切换的,以表明 first_MutableLiveData 第二个获取数据,第二个_MutableLiveData 先获取数据。这只是为了向您说明会发生什么
-
只需在 foo() 所在的类中传递一个 MainThreadExecutor 并在 MainThread 上使用 setValue 而不是 postValue 执行。你不能强迫它。
标签: android mvvm mutablelivedata