Skip to content
Advertisement

Spring WebFlux: Merge Mono and Flux / Put Mono into Flux?

I’m wondering if it is possible to put the value of a Mono as a value into a Flux just like you could append any object to a list. I know there are some methods you could use but none of them fulfills my exact purpose. What I tried so far:

Flux<T> flux;
Mono<T> mono;
Flux.merge(flux, mono); // <- returns Flux<Object>

This doesn’t sound too bad but notice that it does not return Flux<T> as I would need it but Flux<Object>. Same with Flux.concat(flux, mono);. The method Flux.zip(flux, mono); would stop merging as soon as the Mono completes as far as I understand.

Has somebody a solution for this?

Advertisement

Answer

This is what I ended up doing: enter image description here

I have the method return a Flux of the desired type which in my case was an ‘ExtendedResourceModel’. I create a Mono of this type which gets initialized by another method that I commented out to keep this answer as concise as possible. If a certain condition is met I want to also use a Flux from a different source so I use ‘Flux.concat()’ to put all elements into a single Flux. The ‘concat’-method works by subscribing to the first argument, letting it finish, subscribing to the second one and so on. In case of my condition not being met I just use ‘concat’ again but this time with only the Mono which will put the Mono’s element into a new Flux. This way both cases have the same return type.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement