Im using java 17 and I would like to know an efficient way to make calls in parallel using reactive programming.
In the example shown below I have 3 calls to external services. Each one of them fills an object that will be sent in the last call: serviceFour.callServiceFour(resultMap)
.
@Service
public class ExternalServiceImpl {
private final ServiceOne serviceOne;
private final ServiceTwo serviceTwo;
private final ServiceThree serviceThree;
private final ServiceFour serviceFour;
public Mono<String> makeSequentialCalls() {
Map<String, String> resultMap = new LinkedHashMap<>();
return serviceOne.callServiceOne()
.doOnNext(response -> resultMap.put("service1", response))
.flatMap(response -> serviceTwo.callServiceTwo())
.doOnNext(response -> resultMap.put("service2", response))
.flatMap(response -> serviceThree.callServiceThree())
.doOnNext(response -> resultMap.put("service3", response))
// Send the response
.flatMap(response -> serviceFour.callServiceFour(resultMap));
}
}
The idea is that calls to services 1, 2 and 3 are made in parallel and that finally when they finish, service 4 is called to send the complete response.
Thx.