Skip to content
Advertisement

Why many people say that flatmap in reactor is one-to-many?

I’ve read that wonderful answer about the difference between map and flatMap.

And there is a picture that demonstrates flatmap:

enter image description here

And quote:

The map is for synchronous, non-blocking, one-to-one transformations while the flatMap is for asynchronous (non-blocking) One-to-Many transformations.

Based on that picture and quote I understand that flatMap allows the creation of more (or fewer) elements than it was in the initial Flux. But all examples I was able to find contains the same amount of element in the initial sequence after flatMap like here:

JavaScript

3 strings as input and 3 players as output:

JavaScript

My question is:

Is there a way to modify my example to achieve 3 strings as input and 6 (for example) players as output to prove that flatmap could be one-to-many?

Advertisement

Answer

“Many” does not necessarily lead to “more”. The term “one-to-many” is often shortened to 1:N where N stands for anything – it can be zero, one, or even ten.

In your example, you flatMap each element into a single one (Mono.just(..) + Mono#map(..)). There can be various numbers of items depending on implementation.

FlatMap as one to zero

The simplest example where flatMap results in no element:

JavaScript

FlatMap as one to one

This is exactly your example. I would simplify it a bit:

JavaScript
JavaScript

FlatMap as one to many (more than one)

In this case, we yield 2 players from each input (father and junior):

JavaScript
JavaScript
Advertisement