Convert List<Mono<String>> to Flux<String>
Asked Answered
I

3

5

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>

Imparipinnate answered 5/5, 2021 at 3:17 Comment(0)
M
4

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());
Merbromin answered 5/5, 2021 at 3:33 Comment(2)
Is there a inline solution like I can continue the pipeline instead of extracting it to a variable ?Imparipinnate
Before streaming the list ? can you tell me the input collection ? i mean before changing to Mono<String @ImparipinnateMerbromin
D
3

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.

Doxia answered 5/5, 2021 at 11:53 Comment(1)
Good to know Flux.mergeMerbromin
T
1

You can use concat too.

Flux.concat(listOfMono);

In concat, order is always maintained.

Thurgau answered 24/5, 2023 at 15:5 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.