我在MVVM架构上使用了多个MutableLiveData。在ViewModel上,我发布了对象,但片段没有恢复。当片段恢复时,观察者获得MutableLiveData,但不是按照我发布它们的顺序。如何强制获取MutableLiveData的顺序?
ViewModel:
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"})
}发布于 2019-10-10 21:13:30
所以很明显,当我改变观察者在碎片上的顺序时,它们会按照我需要的顺序到达。感谢大家的快速响应!
发布于 2019-10-10 20:37:42
你不能强求你想要的东西。从代码中可以看到,它们通过调用以下命令将结果发布到MainThread:
ArchTaskExecutor.getInstance() 因此,现在需要费心支持两个不同的LiveData对象之间的同步。你的工作就是这么做。这是一个转折点。
只需使用setValue,而不是直接在MainThread上使用postValue。下面是一个例子。
公共类MainThreadExecutor实现Executor {
private final Handler handler = new Handler(Looper.getMainLooper());
@Override
public void execute(Runnable runnable) {
handler.post(runnable);
}
}
public class YourClass {
MutableLiveData first_MutableLiveData = new MutableLiveData<Data>();
MutableLiveData second_MutableLiveData = new MutableLiveData<Data>();
private final Executor executor;
public YourClass(Executor executor) {
this.executor = executor;
}
void foo(){
executor.execute(new Runnable(){
@Override
public void run() {
first_MutableLiveData.setValue(newData);
second_MutableLiveData.setValue(newData);
}
});
}
}https://stackoverflow.com/questions/58322456
复制相似问题