【问题标题】:Post multiple MutableLiveData have no order发布多个 MutableLiveData 没有顺序
【发布时间】: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


【解决方案1】:

你不能强迫你想要什么。从代码中可以看出,他们通过调用将结果发布到 MainThread:

ArchTaskExecutor.getInstance()  

所以现在人们会费心支持两个不同的 LiveData 对象之间的同步。这样做是你的工作。这是一个角落案例。

直接在 MainThread 上使用 setValue,而不是 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);
            }
        });

    }

}

【讨论】:

  • 虽然这个答案是正确的,但我们将不胜感激。
【解决方案2】:

显然,当我更改观察者在片段上的顺序时,它们按照我需要的顺序到达。感谢大家的快速回复!

【讨论】:

  • 其实有时也可以是有序的。他们不切换。执行器在内部使用,它们并行运行。米特夫的回答是正确的。您需要使用 setValue 而不是 postValue 但 setValue 只能在 MainThread 上调用。
猜你喜欢
  • 2023-02-07
  • 2013-07-26
  • 1970-01-01
  • 2017-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多