0

我有一个返回 Observable 的方法,如下所示:

open fun get(): Observable<Response> {

    return if (condition)
        getDataFromApi()
    else
        getDataFromDb()

}

并订阅如下:

                get()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(/*a object of class extending DefaultObserver*/)

当调用 getDataFromDb() 并在一段时间后根据条件调用 getDataFromApi() 时,我遇到了这个问题。对于第一次调用,它工作正常,但在第二次调用 onNext 时,会使用来自 getDataFromDb() 的旧数据响应多次调用 onNext。请让我知道我做错了什么。我对 RxJava 有点陌生。

4

1 回答 1

1

If getDataFromDb() is emitting items and getDataFromApi() is called, the first method will continue to emit till finish. You should unsubscribe from the stream if it is not needed anymore and also add condition in your source in order to stop emitting if observable is unsubscribed.

Also keep in mind that the functions inside an observable do not run till the stream is subscribed.

于 2018-07-11T08:59:22.470 回答