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

Bas Kuis picture Bas Kuis · Nov 20, 2017 · Viewed 8.4k times · Source

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

Answer

pvpkiran picture pvpkiran · Nov 20, 2017

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)