代码之家  ›  专栏  ›  技术社区  ›  ant2009

rxjava2如何在调用它的方法中返回onsuccess的结果?

  •  1
  • ant2009  · 技术社区  · 8 年前
    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) {
                        }
                    });
        }
    

    InSectStorageInteractitorImp.kt中的

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

    非常感谢你的建议,

    1 回复  |  直到 8 年前
        1
  •  2
  •   Alexey Romanov    8 年前

    你不能(好吧,技术上你可以,但是它会打破使用rxjava的点,而且比仅仅改变 getAllSortedInsects 返回 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操心,并为所有异步使用协程。