0

I'm trying to make parallel rest api calls to 5 different backend systems. Each rest api has different endpoints and different response types. I tried to accomplish this by using Webclient. I'm not able to figure out how to "block" the Mono's emitted by each api call at the same time.

Here is my sample code.

Mono<ClientResponse> userDetails = getUserDetails().subscribeOn(Schedulers.parallel());
Mono<ClientResponse> userAccountDetails = getUserAccountDetails().subscribeOn(Schedulers.parallel());

//getUserDetails and getUserAccountDetails does an exchange() and not retrieve() as i need access to the headers.

Tuple2<ClientResponse, ClientResponse> tuple = Mono.zip(userDetails, userAccountDetails).block();

tuple.getT1().bodyToMono(String.class).block()
tuple.getT2().bodyToMono(String.class).block()

The problem with this approach is even if I zipped the ClientResponses, I still have to invoke a block for each item.

Martin Tarjányi
  • 8,863
  • 2
  • 31
  • 49
venky
  • 73
  • 12
  • If you will use block, you will loose the benefits of reactive programming. Better, you think what you need to do on received response and process that asynchronously. – Vikas Sachdeva Oct 29 '20 at 05:18
  • @VikasSachdeva The app is not a true reactive app. I need to make calls to 5 different rest api's. I want to leverage webclient to make these calls async and get a performance boost. I need all the responses before I move to next stage of the process. – venky Oct 29 '20 at 06:28

1 Answers1

1

You can just simply move the bodyToMono method call to the first and second line:

Mono<String> userDetails = getUserDetails().flatMap(r -> r.bodyToMono(String.class));
Mono<String> userAccountDetails = getUserAccountDetails().flatMap(r -> r.bodyToMono(String.class));

Tuple2<String, String> tuple = Mono.zip(userDetails, userAccountDetails).block();

String userDetailsResponse = tuple.getT1();
String userAccountDetailsResponse = tuple.getT2();

Also, note that I removed the subscribeOn(Schedulers.parallel()) operator. As you use WebClient under the hood explicit scheduling is not necessary to achieve concurrency, you get that out of the box.

Martin Tarjányi
  • 8,863
  • 2
  • 31
  • 49