作者:郑青青11_875 | 来源:互联网 | 2023-02-01 18:59
1> CodeCameo..:
我通过这种方法解决了这个问题
private MediatorLiveData> mSectiOnLive= new MediatorLiveData<>();
.
.
.
@Override
public LiveData> getAllSections() {
final LiveData> sectiOns= mDb.sectionDAO().getAllSections();
mSectionLive.addSource(sections, new Observer>() {
@Override
public void onChanged(@Nullable List sectionList) {
if(sectiOnList== null || sectionList.isEmpty()) {
// Fetch data from API
}else{
mSectionLive.removeSource(sections);
mSectionLive.setValue(sectionList);
}
}
});
return mSectionLive;
}
据我所知,`MediatorData`是完全没必要的.你可以使用`sections.observer()`将`Observer`直接添加到原始`LiveData`.
2> snersesyan..:
在下一行,我正在检查sections.getValue(),它总是给我null,虽然我在DataBase中有数据,后来我在onChanged()方法中得到了值.
这是一种正常行为,因为返回LiveData的查询正在异步工作.那一刻的值为null.
所以调用这个方法
LiveData> getAllSections();
你会在这里得到结果
sections.observe(this, new Observer>() {
@Override
public void onChanged(@Nullable List
来自文件:
除非您在构建器上调用allowMainThreadQueries(),否则Room不允许访问主线程上的数据库,因为它可能会长时间锁定UI.异步查询(返回LiveData或RxJava Flowable的查询)不受此规则的约束,因为它们在需要时在后台线程上异步运行查询.