Sobes.tech
Senior

What do map and flatMap do in Mono?

sobes.tech AI

Answer from AI

In reactive programming using Project Reactor, Mono represents an asynchronous stream that can contain 0 or 1 element.

  • map is used to transform the value inside Mono. It takes a function that transforms the element and returns a new Mono with the transformed value.

  • flatMap is used when the transformation function returns another Mono (or Publisher). It "unwraps" the nested Mono, allowing work with asynchronous chains.

Example:

Mono<String> mono = Mono.just("hello");

// map: transform the string to uppercase
Mono<String> upperMono = mono.map(String::toUpperCase);

// flatMap: asynchronously transform the string, returning a Mono
Mono<String> asyncMono = mono.flatMap(s -> Mono.just(s + " world"));

The difference is that map works with synchronous transformation, while flatMap works with asynchronous transformation, returning a new Mono.

What do map and flatMap do in Mono? — Java - sobes.tech