Java RX,为什么这条线被调用了两次而这两条线从未被调用过

Java RX, why this line is called twice and these 2 line never called

我是 Java Rx 的新手,我不知道这是否是一个有效的问题。

我有功能

    public Single<PayResponse> pay(PayRequest apiRequest) {

                return client.initiatePayment(apiRequest)
                        .doOnSuccess(initiatePaymentResponse -> {
                            System.out.println("first");
                            client.confirmPayment(initiatePaymentResponse.getPaymentId())
                                    .doOnSuccess(confirmPaymentResponse -> {System.out.println("second");doConfirmationLogic(confirmPaymentResponse ))}
                                    .doOnError(ex -> {System.out.println("thirs");ex.printStackTrace();logError(ex);});
                        })

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

执行此方法后,我发现 first 被打印了两次,但 secondthird 已打印

这对我来说很奇怪,因为我希望找到 firstsecondthird

有什么想法吗?

为了开始从可观察对象(如 Single<T>)接收发射值,您必须先 subscribe()

您可能只在其他地方订阅了 pay 编辑的 Single return 两次,这就是为什么您看到 first 被打印两次的原因。在您显示的代码中,我可以看到没有订阅那里的任何可观察对象,因此之后不会发生任何事情。

如果你想链接可观察对象,最常见的选择是使用 flatMap 运算符(还有其他选项)。

在您的情况下,它看起来类似于:

public Single<PayResponse> pay(PayRequest apiRequest) {

    return client.initiatePayment(apiRequest)
                .flatMap(initiatePaymentResponse -> {
                        System.out.println("first");
                        return client.confirmPayment(initiatePaymentResponse.getPaymentId();
                })
                .flatMap(confirmPaymentResponse -> {
                        System.out.println("second");
                        return doConfirmationLogic(confirmPaymentResponse);
                })
               .doOnSuccess(confirmationLogicResponse -> System.out.println("third"))
               .doOnError(ex -> {
                        ex.printStackTrace();
                        logError(ex);
                });
} 

然后,您订阅由 pay 在其他地方编辑的单曲 return,如下所示:

...
pay(apiRequest)
     .subscribe(onSuccesValue -> {
             // The whole chain was successful and this is the value returned 
             // by the last observable in the chain (doConfirmationLogic in your case)
      }, onError {
             // There was an error at some point during the chain
      }
...

我假设所有方法 initiatePaymentconfirmPaymentdoConfirmationLogic return SinglesdoConfirmationLogic 最终都是 return正在 Single<PayResponse>。如果不是这种情况,您将需要进行一些小的更改,但您可以大致了解链接可观察对象的工作原理。