如何使用ConnectableObservable预取并随后使用不同订户的已处理数据

问题描述 投票:0回答:1

在我的应用程序中,我需要在应用程序启动后立即加载大量数据。此外,我需要在某些片段/活动中加载数据时收到一个事件。

我正在使用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()吗?

java android rx-java observable rx-android
1个回答
3
投票

试试这个:

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

请注意:

  1. 你应该保持Observable的相同实例,否则你无法获得重播价值
  2. 你应该使用autoConnect()的其他重载例如autoConnect(int numberOfSubscribers, @NonNull Consumer<? super Disposable> connection)并为你的上游源获得一次性(订阅RxJava 1.x)。
© www.soinside.com 2019 - 2024. All rights reserved.