我有点困惑为什么下面的代码不能工作:
MutableLiveData<String> mutableTest = new MutableLiveData<>();
MediatorLiveData<String> mediatorTest = new MediatorLiveData<>();
mediatorTest.addSource(mutableTest, test -> {
Timber.d(test);
});
mutableTest.setValue("bla!");这段代码看起来很简单,但是调试器不会进入回调,控制台也不会记录任何内容……
编辑:这样就不能正常工作了吗?
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!");发布于 2017-08-15 08:31:26
这个答案在很大程度上复制了@CommonsWare已经在上面的评论部分分享的内容。
为了触发MediatorLiveData的addSource方法上的回调,还需要观察MediatorLiveData对象本身。
这背后的逻辑是,“中介者”在它观察到的LiveData对象和数据的最终使用者之间进行中介。因此,中介者既是观察者又是可观察者,当没有活动的观察者时,不会为中介者触发addSource上的回调。
例如,根据谷歌的安卓架构组件,一个活动或片段可以有一个观察者观察ViewModel上的中介者,而中介者又可以观察在ViewModel中处理的其他LiveData对象或对实用程序类的引用。
@CommonsWare指出了公开方法map和switchMap的转换类的使用,但这些不在我的用例范围内,尽管它们值得检查。
发布于 2018-04-17 22:11:10
我之所以来到这里,是因为我有或多或少相同的经历,而不是使用MediatorLiveData.getValue()。我没有意识到这是一个问题,直到我面对它的时候。我的问题可以这样表述:
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(...)也存在同样的问题,返回的LiveData的getValue()不一定返回最新的值,除非观察到它。
https://stackoverflow.com/questions/45679896
复制相似问题