I am working on a task which I have to reduce a list of Mono to a single Mono.
fun isValid(val: Int): Mono<Boolean> {
return Mono.just(true)
}
fun checkValue(): Mono<Boolean> {
val times = listOf(5, 10)
return times.map{
isValid(it)
}.reduce()
}
Would someone able to help with finding a way to reduce a list of Mono's to a single Mono
CodePudding user response:
Combine the Monos into a Flux. Then apply the reduce
operator.
Given a list of Mono<Boolean>
:
List<Mono<Boolean>> monos = listOf(
Mono.just(true),
Mono.just(false)
);
Combine them into a Flux:
Flux<Boolean> flux = Flux.merge(monos);
// or if you want sequential evaluation instead of concurrent...
// Flux<Boolean> flux = Flux.concat(monos);
Apply the reduce operator:
Mono<Boolean> reduced = flux.reduce((a, b) -> a && b);
// if you only need at least one value to be true, replace && with ||
And finally evaluate it:
Boolean evaluated = reduced.block();
All together, the whole thing looks like this:
Boolean evaluated = Flux.merge(monos)
.reduce((a, b) -> a || b)
.block();