I have this chain of actions to orchestrate:
boolean checkUserPayment(Long userId)
UserInformation fetchUserInformationFromAPI(Long userID)
return Mono.just(PaymentResponse.alreadyPaid(userId))
UserInformation fetchUserInformationFromAPI(Long userID)
yields a value thenPaymentResponse sendPaymentRequest(PaymentRequest paymentRequest)
return Mono.just(PaymentResponse.Error(throwable)
So all in all i want a method like:
Mono<PaymentResponse initiatePayment(Long userID)
which orchestrates the above steps ...
Does Mono
support such scenarios?
Thanks for your input!
EDIT: Based on the first answer, i want a single method, because all the subsequent steps are methods too. So in a non reactive way, it would look like this:
public PaymentResponse(Long userId){
if(checkUserPayment(userId){
return PaymentResponse.AlreadyPaid(userId);
}
UserInformation ui = fetchUserInformationFromAPI(Long userID);
if(ui == null) return PaymentResponse.Error(userId)
PaymentResponse pr = sendPaymentRequest(PaymentRequest paymentRequest);
if(pr == null) return PaymentResponse.Error(userId);
return pr;
}
I have this chain of actions to orchestrate:
boolean checkUserPayment(Long userId)
UserInformation fetchUserInformationFromAPI(Long userID)
return Mono.just(PaymentResponse.alreadyPaid(userId))
UserInformation fetchUserInformationFromAPI(Long userID)
yields a value thenPaymentResponse sendPaymentRequest(PaymentRequest paymentRequest)
return Mono.just(PaymentResponse.Error(throwable)
So all in all i want a method like:
Mono<PaymentResponse initiatePayment(Long userID)
which orchestrates the above steps ...
Does Mono
support such scenarios?
Thanks for your input!
EDIT: Based on the first answer, i want a single method, because all the subsequent steps are methods too. So in a non reactive way, it would look like this:
public PaymentResponse(Long userId){
if(checkUserPayment(userId){
return PaymentResponse.AlreadyPaid(userId);
}
UserInformation ui = fetchUserInformationFromAPI(Long userID);
if(ui == null) return PaymentResponse.Error(userId)
PaymentResponse pr = sendPaymentRequest(PaymentRequest paymentRequest);
if(pr == null) return PaymentResponse.Error(userId);
return pr;
}
Reactive supports such type of scenarios. A general advice would be to split the execution in smaller methods. have a look at above sample.
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)));
}