Skip to content
Advertisement

How to convert Flux<List> into Mono<List>

I have a service which returns Flux<List<Integer>> and I would like to convert it into Mono<List<Integer>> to be used inside transform()

Here is what I did by using flatMap and Mono.just():

JavaScript

But what I would like is to use transform instead:

JavaScript

Is there any operator or technique to make method2 to work? As a result I expect onNext() be called 2 times each with value of List

I know filterAndMap method could be simplified and be used without any complication but actual method is huge(just modified for clarity) and there are many operators in a chain that I want to reuse by avoiding duplications.

Update:

A little bit context what I want to achieve. I have 2 services – one via Http which returns me Mono<List<Integer>> and another one via Redis which returns Flux<List<Integer>>. For both cases I have the exact same functionality – chain of 10-15 operators and what I want to achieve is to avoid duplicate code.

For example:

JavaScript

Maybe better to not concentrate to convert Flux to Mono but instead convert Mono to Flux which I guess much easier?

Update2:

I have changed my existing filterAndMap into Flux. And instead of converting Flux to Mono I went with Mono to Flux

now I can call Flux.transform(this::filterAndMap) and Mono.transform(mono -> this.filterAndMap(mono.flux())) accordingly

JavaScript

Thanks @Michael Berry, even I have changed the implementation, your solution fully covers my initial question/issue. So I accept it.

And thanks to @Simon Baslé for a good call, I have redesign my transformer and went with safer approach(Mono to Flux)

Advertisement

Answer

As per the comments, taking the question here as “How do I apply the same transformation to both a Mono and a Flux without duplicating the code?”

You could use a simple utility function like so:

JavaScript

This function can then be used on any transformer of any type. You can then use the transformation function as-is for a Flux:

JavaScript

…and applying a quick utility method for the Mono:

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