What is the principal difference between these in terms of Mono
?
From the documentation, I read that flatMap
acts asynchronous and map
synchronous. But that doesn't really make sense for me b/c Mono is all about parallelism and that point isn't understandable. Can someone rephrase it in a more understandable way?
Then in the documentation for flatMap
stated (https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#flatMap-java.util.function.Function-):
Transform the item emitted by this Mono asynchronously, returning the
value emitted by another Mono (possibly changing the value type).
Which another Mono is meant there?
Both of the functions map() and flatMap are used for transformation and mapping operations. map() function produces one output for one input value, whereas flatMap() function produces an arbitrary no of values as output (ie zero or more than zero) for each input value. Where R is the element type of the new stream.
Similar to map, the flatMap operator has a single parameter of type Function. However, unlike the function that works with map, the flatMap mapper function transforms an input item into a Publisher rather than an ordinary object.
flatMap(Function<? super T,? extends Mono<? extends R>> transformer) Transform the item emitted by this Mono asynchronously, returning the value emitted by another Mono (possibly changing the value type).
A Flux object represents a reactive sequence of 0.. N items, while a Mono object represents a single-value-or-empty (0..1) result. This distinction carries a bit of semantic information into the type, indicating the rough cardinality of the asynchronous processing.
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
. That transformation is thus done imperatively and synchronously (eg. transforming a String
into an URL
instance).
The other subtlety with flatMap
is that the operator subscribes to the generated Mono
, unlike what would happen if you passed the same Function
to map
.
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