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.

Share

Contents

How operators work

Every Reactor operator returns a new Flux or Mono that wraps the previous one. Calling map or filter does not touch any data; it only records a step, which is called assembly time. When something subscribes, the subscription travels up the chain, each operator subscribes to the one before it, and then data and signals travel down. Each operator therefore sees onNext, onError and onComplete from upstream, and passes requests and cancellation up, as described on the Reactor basics page.

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(...); on its own line, has no effect at all.

The main operator groups
GroupExamplesPurpose
Transformingmap, mapNotNull, handle, castChange each element, one in, at most one out
Filteringfilter, distinct, take, skip, takeWhileKeep some elements
Empty handlingdefaultIfEmpty, switchIfEmptyFallbacks for a source with no elements
FlatteningflatMap, concatMap, flatMapSequential, switchMapTurn each element into an inner publisher, such as a remote call
Combiningconcat, merge, zip, combineLatest, thenJoin several sources
Batching and aggregatingbuffer, window, groupBy, scan, reduce, collectListGroup or summarize elements
Side effectsdoOnNext, doOnError, doFinallyLogging and metrics without changing the data

The programs ran with Reactor 3.7 on JDK 21. Asynchronous examples use delayElement to stand in for remote calls, so their timings are real but rounded to 100 ms.

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.

Java
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:

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)
  • handle combines map and filter: 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.
  • distinct removed every repeat and kept 5 values; it remembers every value it has seen, so on an endless stream it grows without limit. distinctUntilChanged removed only adjacent repeats, keeping the second 3 because a 5 came between, and needs no memory.
  • takeWhile stopped before the first 8 and left it out; takeUntil stopped at the first 8 and included it.
  • When the filter left nothing, defaultIfEmpty supplied one value and switchIfEmpty a whole replacement sequence.
  • Reactive Streams forbids null elements, so a map that returned null failed with NullPointerException. mapNotNull treats null as "no value" instead, here making the Mono empty.

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.

Java
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):

Output
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
The flatMap variants
OperatorConcurrencyOutput orderMeasured
flatMapAll at once (up to 256 by default)As results arrive: 3, 2, 1About the slowest call
flatMapSequentialAll at onceSource order, buffering early resultsAbout 300 ms
concatMapOne at a timeSource orderThe sum, 600 ms
switchMapOnly the latestResults of the latest element onlyEarlier lookups cancelled

switchMap fits search-as-you-type: ids arriving every 100 ms simulate keystrokes, and each new one cancelled the lookup for the previous, so only user3 was produced. flatMapSequential gives the speed of flatMap with the order of concatMap, at the cost of holding finished results until the earlier ones arrive.

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.

Java
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):

Output
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 flatMap started all 10 calls together, so the batch took about one call's time.
  • flatMap(fn, 2) 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).
  • concatMap ran the calls one after another, 1 at a time, and took about 1 second.
  • map(call) compiled and produced 10 Mono objects, but made 0 calls: a Mono that nobody subscribes to does nothing. The type Flux<Mono<Integer>> is the warning sign; whenever the mapper returns a publisher, use a flatMap variant.

Errors need the same care. If one inner call fails, the error reaches the outer sequence, flatMap cancels all the other calls still in flight, and the whole result fails. When one failed lookup should not spoil the batch, handle it inside the inner publisher, for example flatMap(id -> call(id).onErrorResume(e -> Mono.empty()), 2), so that each element succeeds or is skipped on its own.

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.

Java
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:

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
  • concat subscribed to the digits only after the letters completed. merge subscribed to both at once and emitted in arrival order.
  • zip paired elements by position and stopped when the shorter source ended, so "c" was dropped.
  • Mono.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 a defaultIfEmpty first.
  • combineLatest 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.
  • then waited for "saved" to complete, ignored its value and continued with the next Mono. Mono.when waited for both earlier Monos to complete. These express "do B after A" without passing data along.

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.

Java
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:

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]
  • buffer(4) collected lists of 4, and the last one held the remaining 2. window(4) produced inner Fluxes instead, which can be processed as they fill, here summed to 10, 26 and 19, without first collecting a list.
  • scan emitted every running total, starting with the seed 0; reduce emitted only the final 55.
  • groupBy 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. Avoid groupBy with many distinct keys, because every open group holds resources.
  • The doOn... operators observed the signals without changing them. doFinally ran last and reported how the sequence ended: complete, error or cancel.

buffer and window also accept a duration, and bufferTimeout(size, duration) emits whichever limit is reached first, a common pattern for batching writes to a database.

Choosing an operator

Which operator for which job
NeedUse
Transform each valuemap; mapNotNull when the result may be absent
Transform and maybe drop in one stephandle
Call a service for each value, fastestflatMap with a concurrency limit
Call a service for each value, results in orderflatMapSequential, or concatMap for one at a time
Only the latest request mattersswitchMap
Several independent calls, combinedMono.zip
Two live values that update separatelycombineLatest
Interleave two streamsmerge; one after the other: concat
Do B after A, ignoring A's valuethen or thenMany
Batches for bulk writesbuffer or bufferTimeout
Totals per keygroupBy plus reduce, with few keys

Which thread each operator runs on is covered on the schedulers page, and how to test pipelines like these on the Reactor testing page.