我实施了两个存储库以管理数据。因此,如果数据库中没有数据,则应向API询问。我在其他文章中看到可以使用switchIfEmpty解决此问题,但对我而言不起作用。
我尝试了以下代码。调用了restApiFlavorRepository.query(specification)行,但从未通知订户。
public Observable query(Specification specification) {
final Observable observable = flavorDaoRepository.query(specification);
return observable.map(new Func1() {
@Override
public Observable<List<Flavor>> call(Object o) {
if(((ArrayList<Flavor>)o).isEmpty()) {
return restApiFlavorRepository.query(specification);
}
return null;
}
});
}
和这个
public Observable query(Specification specification) {
final Observable observable = flavorDaoRepository.query(specification);
return observable.switchIfEmpty(restApiFlavorRepository.query(specification));
}
当我应该获得两种口味时,我仍然没有清单。
更新
我要找的是这个...
public Observable query(Specification specification) {
Observable<List<Plant>> query = mRepositories.get(0).query(specification);
List<Plant> list = new ArrayList<>();
query.subscribe(plants -> list.addAll(plants));
Observable<List<Plant>> observable = Observable.just(list);
return observable.map(v -> !v.isEmpty()).firstOrDefault(false)
.flatMap(exists -> exists
? observable
: mRepositories.get(1).query(null));
}
它就像魅力!:)
的switchIfEmpty()
要求源,以便没有任何值,完成切换到第二源:
Observable.empty().switchIfEmpty(Observable.just(1))
.subscribe(System.out::println);
这一个不会切换:
Observable.just(new ArrayList<Integer>())
.switchIfEmpty(Observable.just(Arrays.asList(2)))
.subscribe(System.out::println);
如果您想启用空的“自定义”概念,可以使用filter
:
Observable.just(new ArrayList<Integer>())
.filter(v -> !v.isEmpty())
.switchIfEmpty(Observable.just(Arrays.asList(2)))
.subscribe(System.out::println);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句