解決方案是將RealmResults封裝到Flowable中,並使用最新的backpressure策略。
private io.reactivex.Flowable<RealmResults<_>> getSomeItems() {
return io.reactivex.Flowable.create(new FlowableOnSubscribe<RealmResults<__>>() {
@Override
public void subscribe(FlowableEmitter<RealmResults<__>> emitter)
throws Exception {
Realm realm = Realm.getDefaultInstance();
RealmResults<__> results = realm.where(__.class).findAllSortedAsync("__");
final RealmChangeListener<RealmResults<__>> listener = _realm -> {
if(!emitter.isUnsubscribed() && results.isLoaded()) {
emitter.onNext(results);
}
};
emitter.setDisposable(Disposables.fromRunnable(() -> {
results.removeChangeListener(listener);
realm.close();
}));
results.addChangeListener(listener);
}
}, BackpressureStrategy.LATEST)
.subscribeOn(AndroidSchedulers.mainThread())
.unsubscribeOn(AndroidSchedulers.mainThread());
從境界4.0.0-RC1及以上,這種行爲我上面顯示,使用realmResults.asFlowable()
進行烘烤。
Disposable subscription = realm.where(__.class)
.findAllSortedAsync("__")
.asFlowable()
.filter(RealmResults::isLoaded)
.subscribe(...);
'Realm.getDefaultInstance()。where(VideoBundle.class)'希望不是因爲你永遠不會關閉*那個Realm實例。 – EpicPandaForce
順便說一句,解決方案是用Rx2的東西包裝Realm的東西,https://github.com/realm/realm-java/issues/3497#issuecomment-275375789 – EpicPandaForce