嗨,我正在尝试使用Flatmap创建一系列网络请求,但对如何执行此过程的了解还不够。

目的是这样做:

做networkRequest 1
一旦我从networkRequestOne获得结果,就对该结果做一些逻辑运算,然后执行下一个networkRequestTwo并调用onSuccess并从networkRequestTwo返回响应值。

当前代码:

delegator.requestOne(requestData)
                .flatMap ({  response ->
                    if(response.isSuccessful){
                        cookieStorage.saveSessionCookies(response.header(cookieStorage.COOKIE_HEADER_NAME)!!)
                    }
                    return delegator.requestTwo

                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(object : SingleObserver<ResponseTwo>() {
                    @Override
                    fun onSubscribe(Disposable d) {
                    }

                    @Override
                    fun onSuccess(responseTwo :ResponseTwo) {
                        callback.onSuccess(responseTwo)
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                });

这两个delegator.requestOne和delegator.requestTwo都挂接到了一个返回一个Single可观察对象的改造调用上

最佳答案

您需要在subscribe方法中调用回调有点奇怪。如果您已经有了 Rx ,为什么还需要 cb ?如果返回Single并在实际订阅的地方运行回调代码,就会更加清楚:

...
// don't forget to handle the `disposable`
doSmth(requestData)
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(
            { success -> /* here's your success callback code */},
            { error -> /* handle error here */}
    )
...

fun doSmth(requestData: RequestData): Single<ResponseTwo> = delegator.requestOne(requestData)
        .doOnSuccess(::updateCookies)
        // you can extract the data you need from the first request using `it`
        .flatMap { delegator.requestTwo() }

fun updateCookies(response: Response<ResponseOne>) {
    val cookie = response.header(cookieStorage.COOKIE_HEADER_NAME)!!
    cookieStorage.saveSessionCookies(cookie)
}

更新

如果您仍然需要callback:
// don't forget to handle the `disposable`
delegator.requestOne(requestData)
        .doOnSuccess(::updateCookies)
        .flatMap { delegator.requestTwo() }
        .observeOn(AndroidSchedulers.mainThread())
        .subscribeOn(Schedulers.io())
        .subscribe(
                { success -> callback.onSuccess(success) },
                { error -> callback.onError(error) }
        )

fun updateCookies(response: Response<ResponseOne>) {
    if (response.isSuccessful) {
        val cookie = response.header(cookieStorage.COOKIE_HEADER_NAME)!!
        cookieStorage.saveSessionCookies(cookie)
    }
}

08-27 09:56