I keep seeing examples that use flatMap
for a 1-to-1 operation, like:
Flux.just("a", "b", "c")
.flatMap(s -> Mono.just(s.toUpperCase())
when I would have expected
Flux.just("a", "b", "c")
.map(String::toUpperCase)
(Note: I know I didn't add a subscriber; assume I print them or something)
The use of flatMap
here is to flatten the returned Mono
, right? But why not just use the map
operation as shown? Is it just because the map
operation is synchronous? What use case am I missing?
map: Transform the items emitted by this Flux by applying a synchronous function to each item. flatMap: Transform the elements emitted by this Flux asynchronously into Publishers.
Instead of take(1) , you could use next() . This will transform the Flux into a valued Mono by taking the first emitted item, or an empty Mono if the Flux is empty itself.
Mono#flatMap takes a Function that transforms a value into another Mono . That Mono could represent some asynchronous processing, like an HTTP request. On the other hand, Mono#map takes a Function that transforms a value of type T into another value, of type R .
A Flux object represents a reactive sequence of 0.. N items, whereas a Mono object represents a single value or an empty (0..1) result. Most times, you expect exactly one result or no (zero) result, and not a collection that contains possibly multiple results. In such scenarios, it's more convenient to have a Mono.
I don't think you are missing any. According to the documentation, flatMap is used when you require some asynch work to be done within it.
So the operation you would use here is simple map, since all you need is turn one object into another (lower case into upper case).
From what I noticed, if you want to turn one object into another map is enough. If you want extra asynch work done go with flatMap.
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