Android MediatorLiveData 观察者 [英] Android MediatorLiveData observer

查看:36
本文介绍了Android MediatorLiveData 观察者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对为什么以下代码不起作用感到有些困惑:

I'm a bit confused on why the following code doesn't work:

MutableLiveData<String> mutableTest = new MutableLiveData<>();
MediatorLiveData<String> mediatorTest = new MediatorLiveData<>();
mediatorTest.addSource(mutableTest, test -> {
    Timber.d(test);
});
mutableTest.setValue("bla!");

这段代码看起来很简单,但是调试器没有进入回调,控制台也没有记录任何东西......

This code seems straightforward, however the debugger doesn't enter the callback and nothing is logged to the console...

这不应该工作吗?

    MutableLiveData<String> mutableTest = new MutableLiveData<>();
    MediatorLiveData<String> mediatorTest = new MediatorLiveData<>();
    mediatorTest.observe(loginActivity, str -> Timber.d(str));
    mediatorTest.addSource(mutableTest, str -> Timber.d(str));
    mutableTest.setValue("bla!");

推荐答案

这个答案很大程度上复制了@CommonsWare 在上面的评论部分已经分享的内容.

This answer is largely reproduction of what @CommonsWare has already shared in the comment section above.

为了触发对 MediatorLiveData 的 addSource 方法的回调,还需要观察 MediatorLiveData 对象本身.

In order for the callback on MediatorLiveData's addSource method to be triggered, the MediatorLiveData object needs to be observed itself as well.

这背后的逻辑是中介者"在它观察到的 LiveData 对象和数据的最终消费者之间进行调解.因此,中介者同时是观察者和可观察者,当没有活动的观察者时,不会为中介者触发 addSource 上的回调.

The logic behind this is that the 'mediator' mediates between a LiveData object that it observes, and a final consumer of the data. The mediator is hence an observer and observable simultaneously, and the callback on addSource won't be triggered for the mediator when there are no active observers.

举个例子;根据谷歌的 Android 架构组件,活动或片段可以有一个观察者观察 ViewModel 上的中介,后者又可以观察在 ViewModel 内处理的其他 LiveData 对象或对实用程序类的引用.

As an example; according to Google's Android Architecture Components, an activity or fragment could have an observer observing a mediator on the ViewModel, which in turn may observe other LiveData objects that are handled within the ViewModel or a referenced to an utility class.

@CommonsWare 指出了公开方法 mapswitchMap 的 Transformation 类的使用,但这些不在我的用例范围内,尽管它们值得一试.

@CommonsWare pointed out the use of the Transformation class that exposes methods map and switchMap, but these were not within scope of my use case although they are worth checking out.

这篇关于Android MediatorLiveData 观察者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆