2

I am trying to aggregate the result of 5 service calls in Spring reactive. Each service call makes an external API call and gets a result.

Example:

Mono<A> = serviceCall1(...);
Mono<B> = serviceCall2(...);
Mono<C> = serviceCall3(...);
Mono<D> = serviceCall4(...);
Mono<E> = serviceCall5(...);

What I need to do is to make all these calls in parallel, aggregate the result into a Mono. However, if any call fails, I should still be able to ensure that all calls complete. Some calls may fail, some may succeed.

How can I go about this?

Ram Viswanathan
  • 181
  • 3
  • 14
  • Possible duplicate of [Is it possible to start Mono's in parallel and aggregate the result](https://stackoverflow.com/questions/48172582/is-it-possible-to-start-monos-in-parallel-and-aggregate-the-result) – Robert Moskal Mar 19 '19 at 03:41
  • Thanks Robert. I am planning to try with the zip approach. However, in this case, wouldn't merge be more meaningful to run them in parallel? I need to ensure that all calls run sync and finish and then I return a response to the caller synchronously. – Ram Viswanathan Mar 19 '19 at 03:56

2 Answers2

0

All you need to use is the zip operation in Mono. Just make sure you have the onErrorResume fallback in each of the above Monos. Mono.zip then would run when all the values are received of the existing Monos.

0

You can you zip method of Mono where you can pass multiple Mono's. Please find the example below:

Mono<A> monoA = serviceCall1();
Mono<B> monoB = serviceCall2();
Mono<C> monoC = serviceCall3();

Mono.zip(monoA, monoB, monoC).flatMap(tuple -> {
    //here tuple will contain combined response of 3 Mono's which you have passed 
    //in zip method
    // tuple.getT1() will give you response of MonoA (first call)
    // tuple.getT2() will give you response of MonoB (second call)
    // tuple.getT3() will give you response of MonoC (third call)
    // infact you can create new object with response of above 3. 

});

Reference: https://www.tabnine.com/code/java/methods/reactor.core.publisher.Mono/zip

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77