Android MediatorLiveData观察器 [英] Android MediatorLiveData observer

查看:980
本文介绍了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.

作为一个例子;根据Google的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天全站免登陆