Bas Kuis
Bas Kuis

Reputation: 770

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>?

Upvotes: 7

Views: 12664

Answers (2)

Pratik Pawar
Pratik Pawar

Reputation: 91

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));

Upvotes: 2

pvpkiran
pvpkiran

Reputation: 27078

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)

Upvotes: 14

Related Questions