我有这一系列的行动需要协调:
boolean checkUserPayment(Long userId)
UserInformation fetchUserInformationFromAPI(Long userID)
return Mono.just(PaymentResponse.alreadyPaid(userId))
UserInformation fetchUserInformationFromAPI(Long userID)
产生一个值,那么 PaymentResponse sendPaymentRequest(PaymentRequest paymentRequest)
return Mono.just(PaymentResponse.Error(throwable)
总而言之,我想要一个像这样的方法:
Mono<PaymentResponse initiatePayment(Long userID)
协调上述步骤...
Mono
支持这样的场景吗?
感谢您的意见!
Reactive 支持此类场景。一般建议是将执行拆分为更小的方法。看看上面的示例。
public Mono<PaymentResponse> initiatePayment(Long userID){
return Mono.fromSupplier(()->userID)
.map(id->checkUserPayment(id))
.flatMap(pending->pending ? someOtherOperation(userID): Mono.just(PaymentResponse.alreadyPaid(userId)));
}
public Mono<PaymentResponse> someOtherOperation(Long userID){
return Mono.fromSupplier(()->userID)
.map(id->fetchUserInformationFromAPI(id))
.map(userInfo->sendPaymentRequest(PaymentRequest.from(userInfo)))
.onErrorResume(throwable->Mono.just(PaymentResponse.Error(throwable)));
}