Reactor operators: transform, flatten, combine and batch
Reactor has hundreds of operators, but a handful decide how most pipelines behave: the transforming and filtering operators shape each element, the flatMap family controls concurrency and ordering of asynchronous calls, the combining operators join several sources, and the batching operators group elements. Each is shown here with real, measured output from Reactor 3.7.
Contents
How operators work
Every Reactor operator returns a new FluxMonomapfilteronNextonErroronComplete
Two consequences matter in practice. An operator chain is a value you can store and reuse; each subscription runs it again from the start. And because operators are immutable, a call whose result is ignored, such as flux.map(...);
| Group | Examples | Purpose |
|---|---|---|
| Transforming | mapmapNotNullhandlecast | Change each element, one in, at most one out |
| Filtering | filterdistincttakeskiptakeWhile | Keep some elements |
| Empty handling | defaultIfEmptyswitchIfEmpty | Fallbacks for a source with no elements |
| Flattening | flatMapconcatMapflatMapSequentialswitchMap | Turn each element into an inner publisher, such as a remote call |
| Combining | concatmergezipcombineLatestthen | Join several sources |
| Batching and aggregating | bufferwindowgroupByscanreducecollectList | Group or summarize elements |
| Side effects | doOnNextdoOnErrordoFinally | Logging and metrics without changing the data |
The programs ran with Reactor 3.7 on JDK 21. Asynchronous examples use delayElement
Transforming and filtering
The program runs the everyday one-element operators on small inputs chosen so that each one has something to do: strings that are not all numbers, and numbers with repeats, both adjacent and not.
import java.util.List;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class Transforming {
public static void main(String[] args) {
Flux<String> raw = Flux.just("10", "7", "x", "7", "42", "", "3");
// handle: map and filter in one step, with access to a sink
System.out.println("handle (parse, skip bad): " + raw.<Integer>handle((s, sink) -> {
try {
sink.next(Integer.parseInt(s));
} catch (NumberFormatException e) {
// emit nothing for this element
}
}).collectList().block());
Flux<Integer> nums = Flux.just(3, 3, 5, 3, 8, 8, 1, 9);
System.out.println("distinct: " + nums.distinct().collectList().block());
System.out.println("distinctUntilChanged: "
+ nums.distinctUntilChanged().collectList().block());
System.out.println("skip(2).take(3): " + nums.skip(2).take(3).collectList().block());
System.out.println("takeWhile(n < 8): "
+ nums.takeWhile(n -> n < 8).collectList().block());
System.out.println("takeUntil(n == 8): "
+ nums.takeUntil(n -> n == 8).collectList().block());
// Fallbacks for an empty source
Flux<Integer> none = nums.filter(n -> n > 100);
System.out.println("defaultIfEmpty: " + none.defaultIfEmpty(-1)
.collectList().block());
System.out.println("switchIfEmpty: " + none.switchIfEmpty(Flux.just(0, 0))
.collectList().block());
// ofType keeps only elements of one class
Flux<Object> mixed = Flux.just(1, "two", 3.0, "four");
List<String> strings = mixed.ofType(String.class).collectList().block();
System.out.println("ofType(String.class): " + strings);
// Reactive Streams forbids null: a mapper that returns null is an error
Mono<String> lookup = Mono.just("missing-key").map(k -> nullable(k));
try {
lookup.block();
} catch (NullPointerException e) {
System.out.println("map returning null: NullPointerException");
}
System.out.println("mapNotNull instead: "
+ Mono.just("missing-key").mapNotNull(Transforming::nullable)
.defaultIfEmpty("(empty)").block());
}
static String nullable(String key) {
return key.equals("missing-key") ? null : key.toUpperCase();
}
}
Output:
handle (parse, skip bad): [10, 7, 7, 42, 3]
distinct: [3, 5, 8, 1, 9]
distinctUntilChanged: [3, 5, 3, 8, 1, 9]
skip(2).take(3): [5, 3, 8]
takeWhile(n < 8): [3, 3, 5, 3]
takeUntil(n == 8): [3, 3, 5, 3, 8]
defaultIfEmpty: [-1]
switchIfEmpty: [0, 0]
ofType(String.class): [two, four]
map returning null: NullPointerException
mapNotNull instead: (empty)
combineshandle andmap : for each element it may emit one value or none. "x" and the empty string were skipped, so 5 of the 7 strings became numbers.filter removed every repeat and kept 5 values; it remembers every value it has seen, so on an endless stream it grows without limit.distinct removed only adjacent repeats, keeping the second 3 because a 5 came between, and needs no memory.distinctUntilChanged stopped before the first 8 and left it out;takeWhile stopped at the first 8 and included it.takeUntil- When the filter left nothing,
supplied one value anddefaultIfEmpty a whole replacement sequence.switchIfEmpty - Reactive Streams forbids
elements, so anull that returnedmap failed withnull .NullPointerException treatsmapNotNull as "no value" instead, here making the Mono empty.null
flatMap, flatMapSequential, concatMap and switchMap
All four turn each element into an inner publisher, usually an asynchronous call, and flatten the results into one sequence. They differ in how many inner calls run at once and in what order results come out. The fake lookup takes 300, 200 and 100 ms for ids 1, 2 and 3, so later ids finish first and the differences become visible.
import java.time.Duration;
import java.util.List;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class FlatMapFamily {
// A fake remote lookup taking 300, 200 and 100 ms for ids 1, 2 and 3
static Mono<String> lookup(int id) {
return Mono.just("user" + id).delayElement(Duration.ofMillis(400 - id * 100L));
}
static void run(String name, Flux<String> flux) {
long t0 = System.nanoTime();
List<String> result = flux.collectList().block();
long ms = (System.nanoTime() - t0) / 1000000;
System.out.printf("%-10s %-22s about %d ms%n", name, result, Math.round(ms / 100.0) * 100);
}
public static void main(String[] args) {
Flux<Integer> ids = Flux.just(1, 2, 3);
run("flatMap", ids.flatMap(FlatMapFamily::lookup));
run("flatMapSeq", ids.flatMapSequential(FlatMapFamily::lookup));
run("concatMap", ids.concatMap(FlatMapFamily::lookup));
// switchMap cancels the previous inner lookup whenever a new id arrives
Flux<Integer> typing = Flux.just(1, 2, 3).delayElements(Duration.ofMillis(100));
run("switchMap", typing.switchMap(FlatMapFamily::lookup));
}
}
Output (times rounded to 100 ms; the first run includes some JIT warm-up):
flatMap [user3, user2, user1] about 400 ms
flatMapSeq [user1, user2, user3] about 300 ms
concatMap [user1, user2, user3] about 600 ms
switchMap [user3] about 400 ms
| Operator | Concurrency | Output order | Measured |
|---|---|---|---|
flatMap | All at once (up to 256 by default) | As results arrive: 3, 2, 1 | About the slowest call |
flatMapSequential | All at once | Source order, buffering early results | About 300 ms |
concatMap | One at a time | Source order | The sum, 600 ms |
switchMap | Only the latest | Results of the latest element only | Earlier lookups cancelled |
switchMapuser3flatMapSequentialflatMapconcatMap
Limiting concurrency, and the map-instead-of-flatMap mistake
Running every call at once is fast, but a downstream service may not survive 256 parallel requests from each client. The program makes ten 100 ms calls three ways and records how many were in flight at the same moment. It ends with the most common flattening bug.
import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class ConcurrencyLimit {
static final AtomicInteger IN_FLIGHT = new AtomicInteger();
static final AtomicInteger MAX_IN_FLIGHT = new AtomicInteger();
static final AtomicInteger CALLS = new AtomicInteger();
// A remote call of 100 ms that records how many calls run at the same time
static Mono<Integer> call(int id) {
return Mono.defer(() -> {
CALLS.incrementAndGet();
MAX_IN_FLIGHT.accumulateAndGet(IN_FLIGHT.incrementAndGet(), Math::max);
return Mono.just(id * 10).delayElement(Duration.ofMillis(100))
.doOnNext(v -> IN_FLIGHT.decrementAndGet()); // result is back
});
}
static void run(String label, Flux<Integer> flux) {
CALLS.set(0);
MAX_IN_FLIGHT.set(0);
long t0 = System.nanoTime();
int count = flux.collectList().block().size();
long ms = (System.nanoTime() - t0) / 1000000;
System.out.printf("%-26s %2d results, %2d calls, at most %2d at once, about %d ms%n",
label, count, CALLS.get(), MAX_IN_FLIGHT.get(), Math.round(ms / 100.0) * 100);
}
public static void main(String[] args) {
Flux<Integer> ids = Flux.range(1, 10);
ids.flatMap(ConcurrencyLimit::call).blockLast(); // warm-up, not measured
run("flatMap (default 256)", ids.flatMap(ConcurrencyLimit::call));
run("flatMap(fn, 2)", ids.flatMap(ConcurrencyLimit::call, 2));
run("concatMap", ids.concatMap(ConcurrencyLimit::call));
// The classic mistake: map instead of flatMap gives a Flux of unsubscribed Monos
CALLS.set(0);
Flux<Mono<Integer>> nested = ids.map(ConcurrencyLimit::call);
System.out.println("map(call): " + nested.collectList().block().size()
+ " Mono objects, calls actually made: " + CALLS.get());
}
}
Output (times rounded to 100 ms):
flatMap (default 256) 10 results, 10 calls, at most 10 at once, about 100 ms
flatMap(fn, 2) 10 results, 10 calls, at most 2 at once, about 500 ms
concatMap 10 results, 10 calls, at most 1 at once, about 1000 ms
map(call): 10 Mono objects, calls actually made: 0
- Plain
started all 10 calls together, so the batch took about one call's time.flatMap never had more than 2 calls in flight and took about 5 rounds of 100 ms. The second argument is the standard way to protect a service; a third argument sets the prefetch, how many results each inner publisher may queue (32 by default).flatMap(fn, 2) ran the calls one after another, 1 at a time, and took about 1 second.concatMap compiled and produced 10map(call) objects, but made 0 calls: aMono that nobody subscribes to does nothing. The typeMono is the warning sign; whenever the mapper returns a publisher, use a flatMap variant.Flux<Mono<Integer>>
Errors need the same care. If one inner call fails, the error reaches the outer sequence, flatMapflatMap(id -> call(id).onErrorResume(e -> Mono.empty()), 2)
Combining sources
The letters arrive every 100 ms and the digits every 130 ms, so their emissions interleave without ties in timing. The second half combines independent Monos, as a page that needs a profile and an order count would, and then runs a step after another one completes.
import java.time.Duration;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class Combining {
public static void main(String[] args) {
Flux<String> letters = Flux.just("a", "b", "c").delayElements(Duration.ofMillis(100));
Flux<String> digits = Flux.just("1", "2").delayElements(Duration.ofMillis(130));
System.out.println("concat: " + Flux.concat(letters, digits).collectList().block());
System.out.println("merge: " + Flux.merge(letters, digits).collectList().block());
System.out.println("zip: " + Flux.zip(letters, digits, (l, d) -> l + d)
.collectList().block());
// zip of independent Monos: run in parallel, combine when all are done
Mono<String> profile = Mono.just("Ana").delayElement(Duration.ofMillis(300));
Mono<Integer> orders = Mono.just(7).delayElement(Duration.ofMillis(300));
long t0 = System.nanoTime();
String page = Mono.zip(profile, orders)
.map(t -> t.getT1() + " has " + t.getT2() + " orders").block();
System.out.println("Mono.zip: " + page + " (both 300 ms calls took "
+ ((System.nanoTime() - t0) / 1000000 < 500 ? "~300 ms together)" : "longer)"));
// If one Mono in a zip is empty, the whole zip is empty
String empty = Mono.zip(Mono.just("Ana"), Mono.<Integer>empty())
.map(t -> "never").defaultIfEmpty("zip with an empty Mono is empty").block();
System.out.println(empty);
// combineLatest: a new result whenever either source emits, using the latest of each
Flux<String> rate = Flux.just("rate=1.10", "rate=1.12").delayElements(
Duration.ofMillis(100));
Flux<String> amount = Flux.just("amount=50", "amount=80").delayElements(
Duration.ofMillis(130));
System.out.println("combineLatest: " + Flux.combineLatest(rate, amount,
(r, a) -> r + "/" + a).collectList().block());
// then / thenMany: wait for completion, ignore the values
String afterSave = Mono.just("saved").delayElement(Duration.ofMillis(50))
.then(Mono.just("now send the e-mail")).block();
System.out.println("then: " + afterSave);
System.out.println("Mono.when (completion of all): "
+ Mono.when(profile, orders).then(Mono.just("all done")).block());
}
}
Output:
concat: [a, b, c, 1, 2]
merge: [a, 1, b, 2, c]
zip: [a1, b2]
Mono.zip: Ana has 7 orders (both 300 ms calls took ~300 ms together)
zip with an empty Mono is empty
combineLatest: [rate=1.10/amount=50, rate=1.12/amount=50, rate=1.12/amount=80]
then: now send the e-mail
Mono.when (completion of all): all done
subscribed to the digits only after the letters completed.concat subscribed to both at once and emitted in arrival order.merge paired elements by position and stopped when the shorter source ended, so "c" was dropped.zip is the standard way to make independent calls in parallel and combine the results: two 300 ms calls took about 300 ms in total. If any Mono in a zip completes empty, the whole zip completes empty without calling the combinator, so give optional inputs aMono.zip first.defaultIfEmpty produced a result whenever either side emitted, using the newest value of the other: three results from two rates and two amounts. It suits values such as a currency rate and an amount that update independently.combineLatest waited for "saved" to complete, ignored its value and continued with the next Mono.then waited for both earlier Monos to complete. These express "do B after A" without passing data along.Mono.when
Batching, aggregating and side effects
The last group works on many elements at once. The numbers 1 to 10 make the batch sizes and totals easy to check, and five sales in three regions show grouping.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import reactor.core.publisher.Flux;
public class Batching {
record Sale(String region, int amount) {
}
public static void main(String[] args) {
Flux<Integer> ids = Flux.range(1, 10);
System.out.println("buffer(4): " + ids.buffer(4).collectList().block());
System.out.println("window(4) sums: " + ids.window(4)
.flatMap(w -> w.reduce(0, Integer::sum)).collectList().block());
System.out.println("scan (running sum): " + ids.scan(0, Integer::sum)
.collectList().block());
System.out.println("reduce (total): " + ids.reduce(0, Integer::sum).block());
Flux<Sale> sales = Flux.just(new Sale("north", 10), new Sale("south", 5),
new Sale("north", 7), new Sale("east", 3), new Sale("south", 4));
Map<String, Integer> perRegion = sales.groupBy(Sale::region)
.flatMap(g -> g.map(Sale::amount).reduce(Integer::sum)
.map(total -> Map.entry(g.key(), total)))
.collectMap(Map.Entry::getKey, Map.Entry::getValue).block();
System.out.println("groupBy totals: " + perRegion.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.map(e -> e.getKey() + "=" + e.getValue()).collect(Collectors.joining(", ")));
List<String> log = new ArrayList<>();
Flux.just(1, 2)
.doOnSubscribe(s -> log.add("subscribed"))
.doOnNext(n -> log.add("next " + n))
.doOnComplete(() -> log.add("complete"))
.doFinally(sig -> log.add("finally " + sig))
.blockLast();
System.out.println("doOn* hooks: " + log);
}
}
Output:
buffer(4): [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
window(4) sums: [10, 26, 19]
scan (running sum): [0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55]
reduce (total): 55
groupBy totals: east=3, north=17, south=9
doOn* hooks: [subscribed, next 1, next 2, complete, finally onComplete]
collected lists of 4, and the last one held the remaining 2.buffer(4) produced inner Fluxes instead, which can be processed as they fill, here summed to 10, 26 and 19, without first collecting a list.window(4) emitted every running total, starting with the seed 0;scan emitted only the final 55.reduce split the sales by region into one inner Flux per key, each of which must be consumed, here by summing. North is 10 + 7 = 17 and south 5 + 4 = 9. AvoidgroupBy with many distinct keys, because every open group holds resources.groupBy- The
operators observed the signals without changing them.doOn... ran last and reported how the sequence ended: complete, error or cancel.doFinally
bufferwindowbufferTimeout(size, duration)
Choosing an operator
| Need | Use |
|---|---|
| Transform each value | mapmapNotNull |
| Transform and maybe drop in one step | handle |
| Call a service for each value, fastest | flatMap |
| Call a service for each value, results in order | flatMapSequentialconcatMap |
| Only the latest request matters | switchMap |
| Several independent calls, combined | Mono.zip |
| Two live values that update separately | combineLatest |
| Interleave two streams | mergeconcat |
| Do B after A, ignoring A's value | thenthenMany |
| Batches for bulk writes | bufferbufferTimeout |
| Totals per key | groupByreduce |
Which thread each operator runs on is covered on the