我有pay方法,在该方法中,我应该调用initializePayment,在onSuccess中,我应该调用confirmPayment
如果两个调用中的任何一个发生异常,则它应发出一个异常

public Single<PayResponse> pay(PayRequest apiRequest) {

            return client.initiatePayment(apiRequest)
                    .doOnSuccess(initiatePaymentResponse -> {
                        client.confirmPayment(initiatePaymentResponse.getPaymentId())
                                .doOnSuccess(confirmPaymentResponse -> doConfirmationLogic(confirmPaymentResponse ))
                                .doOnError(ex -> {ex.printStackTrace();logError(ex);});
                    })

                    .doOnError(ex -> {ex.printStackTrace();logError(ex);});
        }


在我引用的代码中,confirmPayment中发生错误,但initiatePayment正常继续。

如何将异常从内部doOnError传播到外部doOnError

最佳答案

doOnXxx()方法仅用于回调目的,并且不涉及流传输管道,因此它们被称为“副作用方法”。因此无法将错误从doOnXxx()传播到上游。

错误始终是Rx世界中的终端事件,每当发生错误时,管道都会被取消,因此无需对doOnSuccess()方法做任何事情以确保到目前为止一切都正常。因此,除了将代码嵌套到doOnSuccess()链中之外,您可以简单地以这种方式编写:

/*
        you can deal with errors using these operators:

        onErrorComplete
        onErrorResumeNext
        onErrorReturn
        onErrorReturnItem
        onExceptionResumeNext
        retry
        retryUntil
        retryWhen
         */
        return client.initiatePayment(apiRequest)
                //if in initiatePayment was error this will send cancel upstream and error downstream
                .map(initiatePaymentResponse -> { client.confirmPayment(initiatePaymentResponse.getPaymentId());})
                //if in confirmPayment was error this never happens
                .map(confirmPaymentResponse -> doConfirmationLogic(confirmPaymentResponse))
                //every error in this pipeline will trigger this one here
                .doOnError(ex -> {
                    ex.printStackTrace();
                    logError(ex);
                });

09-13 05:29