I have defined an operator flatReduce() which is to reduce() what flatMap() is to map():
public class FlatReduce {
public static <V, W> Mono<V> flatReduce(Mono<V> initial, Iterable<W> items, BiFunction<V, W, Mono<V>> accumulator) {
for (W item : items) {
initial = initial.flatMap(v -> accumulator.apply(v, item));
}
return initial;
}
public static void main(String[] args) {
flatReduce(Mono.just(1), IntStream.range(0, 4000).mapToObj(it -> it).collect(toList()), (a, b) -> Mono.just(a + b)).block();
}
}
This yields deeply nested flatMaps and I have observed stack overflows. Is there any way to work around this (maybe turning this into continuation style)?
Thanks.