Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to wait for all requests to complete with Spring 5 WebClient?

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 ?

like image 474
kms333 Avatar asked Jun 07 '18 12:06

kms333


1 Answers

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();
like image 160
Brian Clozel Avatar answered Oct 13 '22 02:10

Brian Clozel