Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flux.map vs Flux.flatMap for a 1-to-1 operation

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?

like image 435
kousen Avatar asked Oct 08 '17 18:10

kousen


People also ask

What is flatMap in flux?

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.

How do you convert flux to Mono?

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.

How do you use flatMap with mono?

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 .

What is the difference between mono and flux?

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.


1 Answers

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.

like image 175
Kacper Roszczyna Avatar answered Sep 21 '22 13:09

Kacper Roszczyna