I'm trying to make 9 api calls at the same time. All of these calls would return different response objects. Before this we have 8 api calls and since these mono were different types, I used Mono.zip like below.
Mono<ResponseEntity<Service1Response>> monoService1 = callService1();
Mono<ResponseEntity<Service2Response>> monoService2 = callService2();
...
Mono<ResponseEntity<Service3Response>> monoService7 = callService7();
Mono<ResponseEntity<Service4Response>> monoService8 = callService8();
MixResponse mix = Mono.zip(monoService1, monoService2, monoService3, monoService4, monoService5, monoService6, monoService7, monoService8).flatMap(response -> {
MixResponse mixResp = new MixResponse();
mixResp.setResponse1(response.getT1().getBody());
mixResp.setResponse2(response.getT2().getBody());
mixResp.setResponse3(response.getT3().getBody());
mixResp.setResponse4(response.getT4().getBody());
mixResp.setResponse5(response.getT5().getBody());
mixResp.setResponse6(response.getT6().getBody());
mixResp.setResponse7(response.getT7().getBody());
mixResp.setResponse8(response.getT8().getBody());
return Mono.just(mixResp);
})).block();
but now we have one more service and Mono.zip supports only up to 8 monos. Is there anyway aside from Mono.zip that I could use in my situation? Sorry if this question looks dumb. I'm new in spring-webflux. Thanks in advance.
You could use Mono.zip
that is taking Iterable
as an argument and combinator function to combine results and casting to the specific type:
<R> Mono<R> zip(final Iterable<? extends Mono<?>> monos, Function<? super Object[], ? extends R> combinator)
List<Mono<? extends ResponseEntity<?>>> requests = List.of(
monoService1,
monoService2,
monoService3,
monoService4
);
Mono.zip(requests, responses -> {
MixResponse mixResp = new MixResponse();
mixResp.setResponse1(((ResponseEntity<Service1Response>) responses[0]).getBody());
mixResp.setResponse2(((ResponseEntity<Service2Response>) responses[1]).getBody());
mixResp.setResponse3(((ResponseEntity<Service3Response>) responses[2]).getBody());
mixResp.setResponse4(((ResponseEntity<Service4Response>) responses[3]).getBody());
return mixResp;
});