当通过在查询上调用asObservable()
来使用Realm Observable时,使用amb()
或switchIfEmpty()
会导致域的可观察性无法完成其序列。可以使用Observable.just()
代替Realms asObservable()
来解决此问题。
我无法弄清楚这是由我的代码还是rx-java或Realm中的错误造成的。
mSubscription = getRealmObservable(params).switchIfEmpty(getNetworkObservable(params))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
private Observable<model> getNetworkObservable(UrlParams params) {
final api service = NetworkManager.getAPI();
return service.getModel(params.toMap())
.doOnNext(new Action1<RealmList<Model>>() {
@Override
public void call(RealmList<Model> models) {
if (models != null && models.size() > 0) {
mRealm.beginTransaction();
mRealm.copyToRealmOrUpdate(models);
mRealm.commitTransaction();
}
}
})
.flatMap(new Func1<RealmList<Model>, Observable<Model>>() {
@Override
public Observable<Model> call(RealmList<Model> models) {
return Observable.from(models);
}
});
}
private Observable<Model> getRealmObservable(final UrlParams params) {
return Observable.just(mRealm.where(Model.class).findAll())/*.asObservable()*/ <- Using this cause this sequence not to finish
.filter(new Func1<RealmResults<Model>, Boolean>() {
@Override
public Boolean call(RealmResults<Model> models) {
return models != null && models.isValid() && models.size() > 0;
}
})
.flatMap(new Func1<RealmResults<Model>, Observable<Model>>() {
@Override
public Observable<Model> call(RealmResults<Model> models) {
return Observable.from(models);
}
});
}