[英]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
打印了兩次,但second
和third
second
沒有打印
這對我來說是奇怪的行為,因為我希望找到first
和second
或third
。
任何的想法 ?
為了開始從可觀察對象(如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
}
...
我假設所有的方法initiatePayment
, confirmPayment
, doConfirmationLogic
回報Singles
和doConfirmationLogic
最終返回一個Single<PayResponse>
如果情況並非如此,您將需要進行一些小的更改,但您會大致了解鏈接 observables 的工作原理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.