I have a simple Java program that sends multiple requests with Spring WebClient. Each returns a mono, and I am using response.subscribe() to check the result.
However, my main thread of execution finishes before all requests are processed, unless I add a long Thread.sleep().
With CompletableFutures you can use: CompletableFuture.allOf(futures).join();
Is there a way to wait for all Mono's to complete ?
As explained in the Project Reactor documentation, nothing happens until you subscribe
to a Publisher
. That operation returns an instance of Disposable
, meaning that operation may still be ongoing at that point.
If you're not in the middle of a non-blocking reactive pipeline (for example, an HTTP request/response exchange or a batch operation) and you need to wait for the completion of that pipeline before exiting the VM - then you can block()
. This is actually one of the few "allowed" use cases for that.
Your question doesn't really explain what you mean by "check the response". Here, we'll just get POJOs (if the HTTP response status is not 200 or if we can't deserialize the response, an error signal will be sent). In your example, you could have something like:
Mono<User> one = this.webClient...
Mono<Account> two = this.webClient...
Mono<Book> three = this.webClient...
// we want all requests to happen concurrently
Mono<Void> all = Mono.when(one, two, three);
// we subscribe and then wait for all to be done
all.block();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With