【问题标题】:How can RxJava2 return the result from onSuccess in a method it was called from?RxJava2 如何在调用它的方法中从 onSuccess 返回结果?
【发布时间】:2018-06-02 23:05:58
【问题描述】:
rxjava:2.1.14
rxandroid:2.0.2
Android Studio 3.2 Canary

我有以下方法可以检索已排序行的游标。

但是,这个方法需要返回游标。然而,没有办法 我可以在 onSuccess 方法返回 void 时返回光标。

只是想知道如何从 onSuccess 获取光标并从方法中返回它?

public Cursor queryAllInsects(String sortOrder) {
        insectStorageInteractorImp.getAllSortedInsects(sortOrder)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<Cursor>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onSuccess(Cursor cursor) {
                        return cursor; /* anyway I can return the cursor in this method */
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                });
    }

InsectStorageInteractorImp.kt

override fun getAllSortedInsects(sortOrder: String): Single<Cursor> {
    return Single.fromCallable {
        insectStorageImp.queryAndSort(sortOrder)
    }
}

非常感谢您的任何建议,

【问题讨论】:

  • 您可以拨打Single.blockingGet。但我强烈反对这样做,它首先破坏了拥有 Rx 的全部意义。
  • 请参阅this answer(以及问题,就此而言)以更详细地解释为什么您尝试做的事情是一个坏主意。
  • 为什么需要返回游标?你会用它做什么?你最好返回一个 Singlr 并在 onSuccess 回调中使用该光标做你需要做的一切。

标签: java kotlin rx-java2


【解决方案1】:

你不能(好吧,从技术上讲你可以,但它会破坏使用 RxJava 的意义,并且比仅仅更改 getAllSortedInsects 以返回 Cursor 更糟糕(不要认为这是一个建议更改getAllSortedInsects 以返回Cursor))。

但在 Kotlin 中,您可以做一些看起来非常类似于返回 Cursor 的事情,并且可以类似地与协程一起使用:

public suspend fun queryAllInsects(sortOrder: String): Cursor =
    insectStorageInteractorImp.getAllSortedInsects(sortOrder)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .await()

请参阅https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md 了解协程,了解https://github.com/Kotlin/kotlinx.coroutines/tree/master/reactive/kotlinx-coroutines-rx2 了解 RxJava2 集成。

或者,完全不用 RxJava2 并使用协程来实现所有异步。

【讨论】:

    猜你喜欢
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2015-07-10
    • 2013-01-23
    • 2020-08-15
    • 2019-11-08
    相关资源
    最近更新 更多