I need advice/recommendations. I have not coded the program yet. I plan to code a Spring Boot RESTful web service. In the web service, I'm planning to make several asynchronous calls to other external RESTful web services using Spring Wenflux's WebClient. I need to wait for all these asynchronous call responses until they all have completed before moving to the next program task. The question is how do I wait? I'm planning to record the WebClient's handler object references and have an infinite loop checking that all synchronous responses have been processed. Is there a better way of doing this?
Using webflux and reactive approach never wait or perform blocking operation until you know what you are doing. Use Flux/Mono api to define chain of transformations. In your case, you can execute all the requests by Webclient, obtain their Monos, then define a Mono that completes, when source Monos are finished:
Mono<ResponseObject> apiMethodHandler() {
Mono<SomeServiceResponse> response1Mono = webclient.get()...;
Mono<AnotherServiceResponse> response2Mono = webclient.get()...;
return Mono.when(response1Mono, response2Mono).map(v -> new ResponseObject("all good"));
}
Depending on details some other options are available. For example, if you need all the results to compute a response, you can use .collectList
:
Mono<ResponseObject> apiMethodHandler() {
Mono<ServiceResponse> response1Mono = webclient.get()...;
Mono<ServiceResponse> response2Mono = webclient.get()...;
return Flux.merge(response1Mono, response2Mono)
.collectList(responsesList -> Mono.just(new ResponseObject(responsesList)));
}