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>?
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)
Using block() is actually the only way to get the object from a Mono when it is emitted.
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.
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!
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)
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With