首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >安卓MediatorLiveData观察者

安卓MediatorLiveData观察者
EN

Stack Overflow用户
提问于 2017-08-15 01:33:10
回答 2查看 14.1K关注 0票数 15

我有点困惑为什么下面的代码不能工作:

代码语言:javascript
复制
MutableLiveData<String> mutableTest = new MutableLiveData<>();
MediatorLiveData<String> mediatorTest = new MediatorLiveData<>();
mediatorTest.addSource(mutableTest, test -> {
    Timber.d(test);
});
mutableTest.setValue("bla!");

这段代码看起来很简单,但是调试器不会进入回调,控制台也不会记录任何内容……

编辑:这样就不能正常工作了吗?

代码语言:javascript
复制
    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!");
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-08-15 08:31:26

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

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

这背后的逻辑是,“中介者”在它观察到的LiveData对象和数据的最终使用者之间进行中介。因此,中介者既是观察者又是可观察者,当没有活动的观察者时,不会为中介者触发addSource上的回调。

例如,根据谷歌的安卓架构组件,一个活动或片段可以有一个观察者观察ViewModel上的中介者,而中介者又可以观察在ViewModel中处理的其他LiveData对象或对实用程序类的引用。

@CommonsWare指出了公开方法mapswitchMap的转换类的使用,但这些不在我的用例范围内,尽管它们值得检查。

票数 33
EN

Stack Overflow用户

发布于 2018-04-17 22:11:10

我之所以来到这里,是因为我有或多或少相同的经历,而不是使用MediatorLiveData.getValue()。我没有意识到这是一个问题,直到我面对它的时候。我的问题可以这样表述:

代码语言:javascript
复制
MutableLiveData<String> mutableTest = new MutableLiveData<>();
MediatorLiveData<String> mediatorTest = new MediatorLiveData<>();
mediatorTest.addSource(mutableTest, test -> {
    mediatorTest.value = test;
});
mutableTest.setValue("bla!");
mediatorTest.getValue(); // will be null

我知道这有点简单,但是MediatorLiveData.getValue()不会包含"bla",这样你永远不会知道你是否可以信任getValue(),除非你100%确定它是活动的(有多个oberserver)。

Transformations.map(...)TransformationsswitchMap(...)也存在同样的问题,返回的LiveDatagetValue()不一定返回最新的值,除非观察到它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45679896

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档