Android RxJava:链接两个请求并在其间做一些逻辑

时间:2018-01-05 11:11:02

标签: android kotlin retrofit2 rx-java2 flatmap

您好我正在尝试使用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都连接到一个返回单个可观察的改进调用

1 个答案:

答案 0 :(得分:2)

您需要在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)
    }
}