在我的应用程序中,我需要在应用程序启动后立即加载大量数据。此外,我需要在某些片段/活动中加载数据时收到一个事件。
我正在使用RxJava ConnectableObservable
。我使用replay()
,因为我需要多个订阅者的相同数据。
伪代码:
Observable.create(emitter -> {
try {
Data next = getDataFromDb();
emitter.onNext(next);
emitter.onCompleted();
} catch (SQLiteException e) {
emitter.onError(e);
}
}, Emitter.BackpressureMode.BUFFER)
.toList()
.compose(applySchedulers())
.replay()
现在如果我想预取数据,我应该在应用程序类中使用subscribe
然后在Activity / Fragment中使用connect()
吗?
试试这个:
observable = Observable.create(emitter -> {
try {
Data next = getDataFromDb();
emitter.onNext(next);
} catch (SQLiteException e) {
emitter.onError(e);
}
}, Emitter.BackpressureMode.BUFFER)
.toList()
.compose(applySchedulers())
.replay(1)
.autoConnect()
//start your prefetch
observable.subscribe()//you should better add some log to see the process
//In your Activity
observable.subscribe(/**Your Subscribe**/)// here you will get the replayed value
请注意:
autoConnect()
的其他重载例如autoConnect(int numberOfSubscribers, @NonNull Consumer<? super Disposable> connection)
并为你的上游源获得一次性(订阅RxJava 1.x)。