通常我使用
Observable observable = someObservable.replay().refCount();
来创建一个只执行一次的可观察对象。如果我像下面这样多次订阅observable
,这会很好地工作:
observable.observeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(...);
observable.observeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(...);
observable
只执行一次——完美,正如我想要的那样。如果我现在这样做:
Observable obs1 = observable.map(...); // call some operators
Observable obs2 = observable.map(...); // call some operators
obs1.observeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(...);
obs2.observeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(...);
则执行两次observable
。我怎样才能确保这不会发生呢?
我认为你想要的是添加一个.take(1)
操作符。这样,一旦从可观察对象中读取了内容,它就会调用onComplete.