在我的应用程序中,我试图使用MediatorLiveData来侦听对实时数据的更改。由于涉及到DB操作,所以我使用像这样的executor服务。
MediatorLiveData<Content> mediatorLiveData = new MediatorLiveData<>();
appExecutors.diskIO().execute(() -> {
long id = contentDao.insert(content);
Log.i("LIVE", id + "");
LiveData<Content> content = contentDao.getContentById(id);
mediatorLiveData.addSource(content, new Observer<Content>() {
@Override
public void onChanged(@Nullable Content content) {
Log.i("LIVE", "FIRED");
}
});
});首先,我尝试在db中插入一个新的内容对象。我获得插入对象的id,并将其登录到下一行。我得到了一些身份证明,这很好。之后,我使用id查询同一个对象。查询返回一个LiveData。(如果此时使用content.getValue(),则获得null。)
然后,我使用一个liveData来监听这个MediatorLiveData中的变化。不幸的是,从未触发mediatorLiveData的mediatorLiveData方法。因此,日志也不会被打印。
这是我的内容道课
@Dao
public interface ContentDao {
@Insert
long insert(Content content);
@Query("SELECT * FROM my_table WHERE id = :id")
LiveData<Content> getContentById(long id);
}我不明白我做错了什么。有人能帮忙吗。谢谢!!
编辑:为了澄清,代码就是这样的。
return new NetworkBoundResource<Content, CreateContent>(appExecutors) {
@Override
protected void saveCallResult(@NonNull CreateContent item) {
//Something
}
@Override
protected boolean shouldCall(@Nullable Content data) {
//Something;
}
@Override
protected LiveData<Content> createDbCall() {
MediatorLiveData<Content> mediatorLiveData = new MediatorLiveData<>();
appExecutors.diskIO().execute(() -> {
long id = contentDao.insert(content);
Log.i("LIVE", id + "");
LiveData<Content> content = contentDao.getContentById(id);
mediatorLiveData.addSource(content, new Observer<Content>() {
@Override
public void onChanged(@Nullable Content c) {
Log.i("LIVE", "FIRED");
mediatorLiveData.removeSource(content);
mediatorLiveData.postValue(c);
}
});
});
return mediatorLiveData;
}
@NonNull
@Override
protected LiveData<ApiResponse<CreateContent>> createCall() {
//Something
}
}.asLiveData();该值将返回给构造函数。
@MainThread
public NetworkBoundResource(AppExecutors appExecutors) {
this.appExecutors = appExecutors;
result.setValue(Resource.loading(null));
//TODO:: Add method to check if data should be saved. This should apply for search data.
LiveData<ResultType> dbSource = createDbCall();
result.addSource(dbSource, data -> {
result.removeSource(dbSource);
if (shouldCall(data)) {
fetchFromNetwork(dbSource);
} else {
result.addSource(dbSource, newData -> setValue(Resource.success(newData)));
}
});
}发布于 2018-09-19 13:40:33
如前所述,您需要确保mediatorLiveData附加了一个活动观察者。
如果您查看addSource方法,它将检查在订阅源之前是否附加了任何活动的观察者。
发布于 2021-09-14 05:29:50
如果有人重新初始化中介活数据,则只会观察旧对象,而不会观察新对象。
也就是说,不要这样做:
//在此之后,设置为对象myMediatorObj的任何内容都不会被观察到
如果您试图重置数据,请传入一些发出空/空/rest信号的数据。
https://stackoverflow.com/questions/52404536
复制相似问题