Search code examples
spring-bootspring-webfluxproject-reactorreactor

How to asynchronosuly reduce a Flux to Mono with Reactor


I am trying to figure out how to asynchronously do a reduction of Flux to Mono.

Here is an example:

interface AsyncTask {
    Mono<Result> apply(Result resutl);
}

List<AsyncTask> tasks = ...

Flux.fromIterable(tasks)
    .reduceWith(Result::new, (r, task) -> {
        // This does not compile, it expects Result, not Mono<Result>
        return task.apply(r)
    })

The goal is to sequentially apply a task to a given result and use the result for the next task in the list.


Solution

  • Flux.fromIterable(tasks)
        .reduceWith(() -> Mono.just(new Result()), (result, task) -> {
             return result.flatMap(task::apply);
        });