Operators: map, flatMap, concatMap, switchMap
Mid-level Always asked 7 min
On this page
The question
What is the difference betweenmapandflatMapin Reactor?
30-second answer
map applies a synchronous function, turning each element into one value on the spot. flatMap takes a function returning a Publisher, subscribes to it and flattens its results into the stream. Use map for a calculation and flatMap for anything asynchronous, such as a database or HTTP call. On a Flux, flatMap runs inner calls concurrently, so order can change.
Understand it
One source through six operators
ExploreflatMap starts every inner call at once and passes results on as they finish: 2, 3, 1. Order follows speed, and it ends at 340 ms.
View as text
A marble diagram on a shared timeline. The source lane holds elements 1, 2 and 3 at 0, 100 and 200 ms. The middle shows each inner call as a bar, or a second source with A and B. The output lane shows what comes out, and when. Inner call 2 takes 120 ms and call 3 takes 60 ms.
flatMap starts every inner call at once and passes results on as they finish: 2, 3, 1. Order follows speed, and it ends at 340 ms.
flatMap starts every inner call at once and passes results on as they finish: 1, 2, 3. Order follows speed, and it ends at 260 ms.
concatMap runs one inner call at a time, so order is always 1, 2, 3. Waiting costs time: it ends at 520 ms.
switchMap cancels the running inner call when a new element arrives. Output here: 1, 3. Only a call that finishes in time survives.
merge subscribes to both sources at once and interleaves their elements as they arrive. It waits for neither and pairs nothing.
zip waits for one element from each source, then emits a pair. It ends with the shorter source, so 3 never gets a partner.
A marble diagram on a shared timeline. The source lane holds elements 1, 2 and 3 at 0, 100 and 200 ms. The middle shows each inner call as a bar, or a second source with A and B. The output lane shows what comes out, and when. Inner call 2 takes 120 ms and call 3 takes 60 ms.
flatMap starts every inner call at once and passes results on as they finish: 2, 3, 1. Order follows speed, and it ends at 340 ms.
flatMap starts every inner call at once and passes results on as they finish: 1, 2, 3. Order follows speed, and it ends at 260 ms.
concatMap runs one inner call at a time, so order is always 1, 2, 3. Waiting costs time: it ends at 520 ms.
switchMap cancels the running inner call when a new element arrives. Output here: 1, 3. Only a call that finishes in time survives.
merge subscribes to both sources at once and interleaves their elements as they arrive. It waits for neither and pairs nothing.
zip waits for one element from each source, then emits a pair. It ends with the shorter source, so 3 never gets a partner.
Takeaway: flatMap is fast but unordered, concatMap is ordered but slow, switchMap keeps only the latest, merge interleaves two sources, and zip pairs them.
What order does flatMap emit?
PredictFlux.just(1, 2, 3).flatMap(n -> call(n)). The call for 1 takes 300 ms, for 2 takes 100 ms, and for 3 takes 200 ms.
View as text
A timeline from 0 to 600 ms with one bar per inner call, above an output lane. Flux.just(1, 2, 3).flatMap(n -> call(n)). The call for 1 takes 300 ms, for 2 takes 100 ms, and for 3 takes 200 ms. The learner first predicts the order.
flatMap subscribes to each inner call as its element arrives, without waiting. All three calls run at the same time. Three bars start at 0.
Results go downstream as they finish: 2 at 100 ms, 3 at 200 ms, 1 at 300 ms. The order follows speed, and the whole thing takes 300 ms. The output lane shows 2, 3 and 1.
concatMap waits for each call before starting the next. The order is always 1, 2, 3, but the times add up to 600 ms. The bars run one after another, and the output lane shows 1, 2 and 3.
flatMapSequential runs all three at once, and holds results back so they leave in order. All three leave at 300 ms, at the cost of a buffer. The bars start together, and the output lane shows 1, 2 and 3 side by side at 300 ms.
A timeline from 0 to 600 ms with one bar per inner call, above an output lane. Flux.just(1, 2, 3).flatMap(n -> call(n)). The call for 1 takes 300 ms, for 2 takes 100 ms, and for 3 takes 200 ms. The learner first predicts the order.
flatMap subscribes to each inner call as its element arrives, without waiting. All three calls run at the same time. Three bars start at 0.
Results go downstream as they finish: 2 at 100 ms, 3 at 200 ms, 1 at 300 ms. The order follows speed, and the whole thing takes 300 ms. The output lane shows 2, 3 and 1.
concatMap waits for each call before starting the next. The order is always 1, 2, 3, but the times add up to 600 ms. The bars run one after another, and the output lane shows 1, 2 and 3.
flatMapSequential runs all three at once, and holds results back so they leave in order. All three leave at 300 ms, at the cost of a buffer. The bars start together, and the output lane shows 1, 2 and 3 side by side at 300 ms.
Takeaway: flatMap runs inner calls concurrently, so results arrive in finishing order. Use concatMap when order matters more than speed, and flatMapSequential when both do.
In code
Mono<String> name = Mono.just("ana").map(String::toUpperCase); // plain function
Mono<User> user = Mono.just("42").flatMap(id -> users.findById(id)); // async call
Flux<Order> orders = Flux.just("a", "b", "c")
.flatMap(id -> findOrder(id), 8); // at most 8 at once
Flux<Order> ordered = Flux.just("a", "b", "c")
.concatMap(id -> findOrder(id)); // one at a timeMono<Summary> summary = Mono.zip(findUser(id), findOrders(id)) // both, then one result
.map(pair -> new Summary(pair.getT1(), pair.getT2()));
Flux<Event> all = Flux.merge(clicks(), purchases()); // as they arrive
Flux<Event> inTurn = Flux.concat(today(), yesterday()); // the first, then the second
Flux<Result> latest = queries().switchMap(query -> search(query)); // cancels the old searchFlux.fromIterable(ids)
.flatMap(id -> client.fetch(id), 4) // without the limit, up to 256 inner calls run at once
.collectList();Solve it
Enrich 1,000 orders from a rate-limited API and keep their order
Each order needs its customer from an API that allows 10 concurrent requests and answers in about 100 ms. The output must stay in the input order, for a report. Choose the operator and estimate the time.
- List the constraints. Same order as the input, at most 10 calls at a time, and about 100 ms per call.
concatMap. It keeps the order but makes one call at a time: 1,000 x 100 ms is about 100 seconds.flatMap(f, 10). Ten calls at a time, about 10 seconds, but results arrive in completion order. The report would be shuffled.flatMapSequential(f, 10). It also runs ten at a time, then buffers early results and emits them in source order: about 10 seconds, in order.- Check the trade-off. One slow call holds back everything behind it in the buffer. Add a timeout per call, then
test the order with
StepVerifier.
Flux<EnrichedOrder> report(Flux<Order> orders) {
return orders.flatMapSequential(
order -> customers.get(order.customerId())
.timeout(Duration.ofSeconds(2))
.map(customer -> new EnrichedOrder(order, customer)),
10); // concurrency: the API's limit
}How to answer
mapwith a function returning a Mono givesMono<Mono<T>>, and the inner one never runs.flatMapsubscribes for you, so the inner call really happens.- An inner Mono that completes empty adds nothing to the output.
- A
mapfunction must not return null.
Common mistakes
- Doing blocking work in
map, as it runs on the same thread as the stream. - Using
flatMapon a Flux and assuming the output keeps the source order.
Follow-up questions
What is the difference between flatMap and concatMap in ordering?
flatMap subscribes to inner publishers eagerly, up to 256 at once by default, and emits results as they finish, so order follows speed. concatMap subscribes to one at a time, waiting for each to complete, so order is preserved but the times add up. With calls of 300, 100 and 200 ms, flatMap takes 300 ms and concatMap takes 600.
flatMap(fn, 1)behaves likeconcatMap.flatMapSequentialruns concurrently and restores the order, at the cost of a buffer.- Use
concatMapwhen order matters, as with updates to the same account.
See it in the infographic: What order does flatMap emit? See it in the infographic: One source through six operators
What do zip and merge do?
zip waits for one element from each source and combines them, so it pairs by position and ends when the shortest source ends. merge subscribes to all sources at once and interleaves elements as they arrive, without combining them. Use Mono.zip to call two services in parallel and join the answers. concat differs from both: it runs sources one after another.
- If any source of
zipcompletes empty, the zip completes with no result. Mono.zipfails as soon as one source fails, and cancels the others.mergeneeds sources of the same type.
When would you use switchMap?
When only the newest element matters, such as search-as-you-type. Each new element cancels the inner call still running and starts a new one, so a slow answer to an old query can never overwrite a newer one. Do not use it for writes, because cancelling can lose work: use concatMap there.
- In-flight calls are cancelled, so their results never arrive.
- It saves work, as the server may stop processing a cancelled call.
- A slow inner call with a fast source may never emit at all.
You use flatMap to call a service for each of 10,000 elements. What could go wrong, and how do you limit it?
By default it runs 256 inner calls at once, which can overload the service or exhaust a connection pool. Pass a concurrency argument, as in flatMap(fn, 16), which keeps only 16 in flight and requests more as they finish. This is backpressure at work: the limit reaches the source, because flatMap only requests what it can run.
- The default of 256 is
Queues.SMALL_BUFFER_SIZE, and a measured peak was exactly 256. - Size the limit to the service's capacity and the connection pool.
flatMap(fn, 1)is sequential.
Why can Flux.interval(...).concatMap(slowCall) fail with an OverflowException?
A timer cannot wait. concatMap requests only what it can handle, so while one slow call runs, demand reaches zero, and the next tick has nowhere to go. Flux.interval then fails with OverflowException instead of silently losing a tick. Choose what to do: onBackpressureDrop skips ticks, and onBackpressureBuffer queues them.
- It only fails when a call outlasts the tick, so it can pass in tests and fail under load.
flatMaphides this longer, because it runs up to 256 at once.
What happens if the function in map returns null?
The stream fails with a NullPointerException saying the mapper returned null, because Reactive Streams forbids null elements. To skip a value, use flatMap returning Mono.empty(), or handle, which can emit nothing for an element.
Why does Mono.flatMap keep order when Flux.flatMap does not?
A Mono has at most one element, so there is only one inner call and nothing to reorder. A Flux has many elements, each with an inner call running at the same time, so they finish in whatever order their speed decides.
Check yourself
Show answers
- Mono<Mono<User>>: Correct. map wraps the return value as it is, and the inner Mono is never subscribed.
- Mono<User>: Incorrect. That is what flatMap gives, because it subscribes and flattens.
- It does not compile.: Incorrect. It compiles. That is why this mistake is easy to miss.
Show answers
- concatMap: Correct. It waits for each call to complete before starting the next.
- flatMap: Incorrect. Calls run concurrently and can finish in any order.
- switchMap: Incorrect. It cancels running calls, so updates would be lost.
Show answers
- 2 pairs, then it completes.: Correct. It ends with the shortest source, and the third element has no partner.
- 3 pairs, with a null in the last one.: Incorrect. Reactive Streams forbids nulls, and zip emits complete pairs only.
- 5 elements, interleaved.: Incorrect. That is merge. zip pairs by position.