Convert List<Mono<String>> to Flux<String>

Viewed 759

There are few question , but there answers are very specific to some code.

Generally, how to convert a Stream of Mono to Flux

List<Mono<String> listOfMono = stream()
.map( s -> { do something and return Mono<String> } )
.collect(Collectors.toList());

How to convert listOfMono object to Flux<String>

2 Answers

You can use fromIterable and then use flatMap to flatten the Mono

Transform the elements emitted by this Flux asynchronously into Publishers, then flatten these inner publishers into a single Flux through merging, which allow them to interleave.

Flux<String> result = Flux.fromIterable(listOfMono)
            .flatMap(Function.identity());

If your input is a list of Monos you can simply do:

Flux.merge(listOfMono);

If your input is stream you can either do

stream()
   .map( s -> { do something and return Mono<String> } )
   .collect(Collectors.collectingAndThen(Collectors.toList(), Flux::merge));

OR

Flux.fromStream(stream())
    .flatMap( s -> { do something and return Mono<String> } )

I'd personally prefer the last option as that is the most straighforward and idiomatic.

Related