簡體   English   中英

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 second沒有打印

這對我來說是奇怪的行為,因為我希望找到firstsecondthird

任何的想法 ?

為了開始從可觀察對象(如Single<T> )接收發出的值,您必須先subscribe()到它。

您可能只訂閱了在其他地方兩次通過pay返回的Single ,這就是為什么您會看到first打印兩次。 在您顯示的代碼中,我可以看到沒有訂閱那里的任何可觀察對象,因此之后不會發生任何事情。

如果你想鏈接 observables,最常見的選擇是使用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返回的單曲,如下所示:

...
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回報SinglesdoConfirmationLogic最終返回一個Single<PayResponse> 如果情況並非如此,您將需要進行一些小的更改,但您會大致了解鏈接 observables 的工作原理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM