I'm making multiple mono calls to DB.And result of all Mono response is needed to compute final result which is written after declared Mono logic.
if (SomeObject.getAccountLevelActiveList() != null) {
SomeObject.getAccountLevelActiveList().parallelStream().forEach(account -> {
Mono<SubLine> subLineMono= SubLineService
.getLineLevelCustProfile(preNbsLineLevelConverter.getSubLine(account ));
subLineMono.subscribe(subLine-> PollObject.getSubList()
.put(accountLevelMtn.getMtn(), Optional.ofNullable(subLine)));
});
}
But my main logic is getting executed before mono result stored to the PollObject. so i'm getting null in the PollObject. So i want to stop my main thread until Mono results stored into the PollObject.
If you want to stop main thread then you can use blocking instead of subscribing, but you must first convert the
List
intoFlux
and thenflatMap
-it using providedMono
. The logic you have in thesubscribe
method can be moved into a side effect operatordoOnNext
either of theMono
or the wrappingFlux
:If your code following the
if
is not required to run in the main thread, it would be better stay reactive as the @chrylis-cautiouslyoptimistic already suggested. Usereduce
operator to put all the result together producing mono that is completed when all the provided monos are completed: