kousen
kousen

Reputation: 3157

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?

Upvotes: 8

Views: 5188

Answers (1)

Kacper Roszczyna
Kacper Roszczyna

Reputation: 219

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.

Upvotes: 12

Related Questions