Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Project Reactor. Mono.map() vs Mono.flatMap()

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?

like image 396
Roman T Avatar asked Jun 07 '19 14:06

Roman T


People also ask

What is the difference between map and flatMap?

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.

What is flatMap in reactor?

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.

What is flatMap in mono?

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

What is the difference between mono and flux?

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.


1 Answers

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.

like image 76
Simon Baslé Avatar answered Oct 04 '22 14:10

Simon Baslé