作者:可燕戏天 | 来源:互联网 | 2022-12-04 14:05
在我的应用程序中,我尝试使用MediatorLiveData收听实时数据的更改。由于涉及数据库操作,因此我使用像这样的执行程序服务。
MediatorLiveData mediatorLiveData = new MediatorLiveData<>();
appExecutors.diskIO().execute(() -> {
long id = contentDao.insert(content);
Log.i("LIVE", id + "");
LiveData cOntent= contentDao.getContentById(id);
mediatorLiveData.addSource(content, new Observer() {
@Override
public void onChanged(@Nullable Content content) {
Log.i("LIVE", "FIRED");
}
});
});
首先,我尝试将新的内容对象插入数据库。我得到插入对象的ID,该对象在下一行中登录。我得到一些很好的身份证。之后,我使用id来查询相同的对象。查询返回一个LiveData。(如果此时使用content.getValue(),则为null。)
然后,我使用收听此liveData中的更改MediatorLiveData
。不幸的是,从未触发mediatorLiveData的onChange方法。因此,也不会打印日志。
这是我的内容道课
@Dao
public interface ContentDao {
@Insert
long insert(Content content);
@Query("SELECT * FROM my_table WHERE id = :id")
LiveData getContentById(long id);
}
我不明白我在做什么错。有人可以帮忙吗?谢谢!!
编辑:澄清一下,这就是代码的外观。
return new NetworkBoundResource(appExecutors) {
@Override
protected void saveCallResult(@NonNull CreateContent item) {
//Something
}
@Override
protected boolean shouldCall(@Nullable Content data) {
//Something;
}
@Override
protected LiveData createDbCall() {
MediatorLiveData mediatorLiveData = new MediatorLiveData<>();
appExecutors.diskIO().execute(() -> {
long id = contentDao.insert(content);
Log.i("LIVE", id + "");
LiveData cOntent= contentDao.getContentById(id);
mediatorLiveData.addSource(content, new Observer() {
@Override
public void onChanged(@Nullable Content c) {
Log.i("LIVE", "FIRED");
mediatorLiveData.removeSource(content);
mediatorLiveData.postValue(c);
}
});
});
return mediatorLiveData;
}
@NonNull
@Override
protected LiveData> 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 dbSource = createDbCall();
result.addSource(dbSource, data -> {
result.removeSource(dbSource);
if (shouldCall(data)) {
fetchFromNetwork(dbSource);
} else {
result.addSource(dbSource, newData -> setValue(Resource.success(newData)));
}
});
}
小智..
7
如前所述,您需要确保mediatorLiveData附加了活动的观察者。
如果您查看addSource方法,则在订阅源之前,它会检查是否连接了任何活动的观察者。
https://github.com/aosp-mirror/platform_frameworks_support/blob/d79202da157cdd94c2d0c0b6ee57170a97d12c93/lifecycle/livedata/src/main/java/androidx/lifecycle/MediatorLiveData.java#L95
1> 小智..:
如前所述,您需要确保mediatorLiveData附加了活动的观察者。
如果您查看addSource方法,则在订阅源之前,它会检查是否连接了任何活动的观察者。
https://github.com/aosp-mirror/platform_frameworks_support/blob/d79202da157cdd94c2d0c0b6ee57170a97d12c93/lifecycle/livedata/src/main/java/androidx/lifecycle/MediatorLiveData.java#L95