Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we convert a Mono<List<Type>> to a Flux<Type>

Using spring 5, with reactor we have the following need.

Mono<TheResponseObject> getItemById(String id){
    return webClient.uri('/foo').retrieve().bodyToMono(TheResponseObject)
}

Mono<List<String>> getItemIds(){
    return webClient.uri('/ids').retrieve().bodyToMono(List)
}

Mono<RichResonseObject> getRichResponse(){
    Mono<List> listOfIds = Mono.getItemIds()
    listOfIds.each({ String id ->
        ? << getItemById(id) //<<< how do we convert a list of ids in a Mono to a Flux
    })
    Mono<Object> someOtherMono = getOtherMono()
    return Mono.zip((? as Flux).collectAsList(), someOtherMono).map({
        Tuple2<List, Object> pair ->
        return new RichResonseObject(pair.getT1(), pair.getT2())
    }).cast(RichResonseObject)
}

What approaches are possible to convert a Mono<List<String>> to a Flux<String>?

like image 447
Bas Kuis Avatar asked Nov 20 '17 19:11

Bas Kuis


People also ask

How do you make Flux?

The generate() method of the Flux API provides a simple and straightforward programmatic approach to creating a Flux. The generate() method takes a generator function to produce a sequence of items. There are three variants of the generate method: generate(Consumer<SynchronousSink<T>> generator)

How do I get a list from Mono list?

Using block() is actually the only way to get the object from a Mono when it is emitted.

What is the difference between mono and Flux?

Mono is more relatable to the Optional class in Java since it contains 0 or 1 value, and Flux is more relatable to List since it can have N number of values.

How do you extract data from a mono object?

Extract data from Mono in Java – blocking way This way of extracting data is discouraged since we should always use the Reactive Streams in an async and non-blocking way. We can use the block() method that subscribes to a Mono and block indefinitely until the next signal is received. Output: Data from Mono: Hello!


2 Answers

This should work. Given List of Strings in Mono

  Mono<List<String>> listOfIds;

  Flux<String> idFlux = listOfIds
    .flatMapMany(ids -> Flux.fromArray(ids.toArray(new String [0])));

Even better would be

listOfIds.flatMapMany(Flux::fromIterable)
like image 135
pvpkiran Avatar answered Sep 28 '22 22:09

pvpkiran


Please find below code : 1st convert Mono<List<String>> to Flux<List<String>> and the convert Flux<List<String>> to Flux<String>

List<String> asList = Arrays.asList("A", "B", "C", "D");
Flux<String> flatMap = Mono.just(asList).flux().flatMap(a-> Flux.fromIterable(a));

Or you can use flatmapmany :

Flux<String> flatMapMany = Mono.just(asList).flatMapMany(x-> Flux.fromIterable(x));
like image 22
Pratik Pawar Avatar answered Sep 28 '22 21:09

Pratik Pawar