Project Reactor basics: Mono and Flux

Project Reactor implements Reactive Streams for Java and is the foundation of Spring WebFlux. Its two types, Mono for zero or one value and Flux for many, describe asynchronous pipelines that run only when something subscribes, and that carry demand back from the consumer to the source. This page explains that model, shows every signal as it passes, and runs creation, backpressure, errors and hot and cold sources with Reactor 3.7.

Share

Contents

The model: publishers, subscribers and demand

Reactor builds on the Reactive Streams specification, four small interfaces that the JDK also ships as java.util.concurrent.Flow since Java 9. A Publisher produces values, a Subscriber consumes them, and a Subscription connects the two. The conversation always follows the same order:

  1. The subscriber calls publisher.subscribe(subscriber), and the publisher answers with onSubscribe(subscription).
  2. The subscriber calls subscription.request(n) to say how many values it can take. This is demand, and it is what backpressure means: a fast source may not send more than was requested.
  3. The publisher sends up to n values with onNext, and ends with exactly one onComplete or onError, or stops when the subscriber calls cancel().

Reactor adds two publisher types with hundreds of operators. Mono<T> emits at most one value, like an asynchronous Optional; Flux<T> emits any number. Each operator, such as map or filter, is itself a subscriber to the stage before it and a publisher to the stage after it, so a pipeline is a chain of small publishers that is assembled first and run later.

Reactor types compared with similar Java types
TypeSinceValuesLazyAsynchronousBackpressure and cancellation
java.util.stream.StreamJava 8ManyYesNoNo; the consumer pulls
CompletableFutureJava 8OneNo; runs when createdYesCancellation only
java.util.concurrent.FlowJava 9ManyInterfaces onlyYesYes, but no operators
MonoReactor 3.0Zero or oneYesOptionalYes
FluxReactor 3.0Zero to infiniteYesOptionalYes

The programs on this page ran with Reactor 3.7 (reactor-core) on JDK 21. Later pages cover operators, threads and schedulers and testing.

Mono, Flux and laziness

A Flux or Mono is a description of work, not the work itself. Nothing runs until something subscribes, here through block() or collectList(). The first pipeline logs every element the source emits, so you can see exactly how much work happens.

Java
import java.time.Duration;
import java.util.List;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class MonoAndFlux {

    public static void main(String[] args) {
        // Nothing happens until something subscribes: this pipeline is only a description
        Flux<Integer> numbers = Flux.range(1, 10)
                .doOnNext(n -> System.out.println("  emitted " + n))
                .filter(n -> n % 2 == 0)
                .map(n -> n * n)
                .take(3);
        System.out.println("pipeline built, nothing emitted yet");

        List<Integer> squares = numbers.collectList().block();
        System.out.println("squares of the first three even numbers: " + squares);

        // Mono: zero or one value
        Mono<String> user = Mono.just("ana").map(String::toUpperCase);
        Mono<String> missing = Mono.<String>empty().defaultIfEmpty("guest");
        System.out.println("Mono values: " + user.block() + ", " + missing.block());

        // Mono.just evaluates its argument immediately; Mono.fromSupplier waits for a subscriber
        Mono<Long> eager = Mono.just(System.nanoTime());
        Mono<Long> lazy = Mono.fromSupplier(System::nanoTime);
        long a1 = eager.block();
        long a2 = eager.block();
        long b1 = lazy.block();
        long b2 = lazy.block();
        System.out.println("Mono.just gives the same value each time: " + (a1 == a2)
                + ", fromSupplier recomputes: " + (b1 != b2));

        // Asynchronous sources run on other threads; block() waits for them
        String last = Flux.interval(Duration.ofMillis(50)).map(i -> "tick " + i).take(4)
                .doOnNext(t -> System.out.println("  " + t + " on "
                        + Thread.currentThread().getName()))
                .blockLast();
        System.out.println("last: " + last);
    }
}

Output:

Output
pipeline built, nothing emitted yet
  emitted 1
  emitted 2
  emitted 3
  emitted 4
  emitted 5
  emitted 6
squares of the first three even numbers: [4, 16, 36]
Mono values: ANA, guest
Mono.just gives the same value each time: true, fromSupplier recomputes: true
  tick 0 on parallel-1
  tick 1 on parallel-1
  tick 2 on parallel-1
  tick 3 on parallel-1
last: tick 3
  • "pipeline built" printed before any element: building the pipeline did nothing.
  • The source emitted only 1 to 6, not 1 to 10. Once take(3) had three even squares, from 2, 4 and 6, it cancelled the subscription and the range stopped. Demand and cancellation flow upstream.
  • Mono.just(value) evaluates its argument once, when the Mono is created, so every subscriber gets the same timestamp. Mono.fromSupplier runs the code for each subscriber. Wrapping a slow or side-effecting call in just runs it immediately even if nobody ever subscribes, a common mistake.
  • Flux.interval emits on Reactor's parallel scheduler, not the main thread, and blockLast() waits for it. Blocking is fine in tests and main methods, but must not happen inside a reactive application's request handling.

Watching the signals

The doOn... operators observe signals without changing them. The program attaches them to a five-element range and subscribes twice: once with the plain subscribe(), and once with a BaseSubscriber that asks for two elements at a time and cancels after three. It then disposes an infinite interval.

Java
import org.reactivestreams.Subscription;
import reactor.core.Disposable;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.Flux;

import java.time.Duration;

public class Signals {

    public static void main(String[] args) throws Exception {
        // Every Reactive Streams signal, printed as it passes
        Flux<Integer> source = Flux.range(1, 5)
                .doOnSubscribe(s -> System.out.println("onSubscribe"))
                .doOnRequest(n -> System.out.println("request(" + n + ")"))
                .doOnNext(v -> System.out.println("onNext(" + v + ")"))
                .doOnComplete(() -> System.out.println("onComplete"))
                .doOnCancel(() -> System.out.println("cancel"));

        System.out.println("--- subscribe(): unbounded demand ---");
        source.subscribe();

        // A subscriber that asks for two elements at a time: backpressure
        System.out.println("--- a subscriber that requests 2 at a time ---");
        source.subscribe(new BaseSubscriber<Integer>() {
            int received;

            @Override
            protected void hookOnSubscribe(Subscription subscription) {
                request(2);
            }

            @Override
            protected void hookOnNext(Integer value) {
                received++;
                if (received == 3) {
                    cancel();                               // no more, thanks
                } else if (received % 2 == 0) {
                    request(2);
                }
            }
        });

        // subscribe() returns a Disposable: disposing it cancels the subscription
        System.out.println("--- disposing an infinite interval ---");
        Disposable ticking = Flux.interval(Duration.ofMillis(100))
                .doOnCancel(() -> System.out.println("interval cancelled"))
                .subscribe(t -> System.out.println("tick " + t));
        Thread.sleep(350);
        ticking.dispose();
        System.out.println("disposed: " + ticking.isDisposed());
    }
}

Output:

Output
--- subscribe(): unbounded demand ---
onSubscribe
request(9223372036854775807)
onNext(1)
onNext(2)
onNext(3)
onNext(4)
onNext(5)
onComplete
--- a subscriber that requests 2 at a time ---
onSubscribe
request(2)
onNext(1)
onNext(2)
request(2)
onNext(3)
cancel
--- disposing an infinite interval ---
tick 0
tick 1
tick 2
interval cancelled
disposed: true
  • The plain subscribe() requested 9,223,372,036,854,775,807 elements, Long.MAX_VALUE, which the specification defines as "unbounded". All five values followed, then onComplete.
  • The custom subscriber requested 2 and received exactly 2. Its second request(2) let one more through, and then it cancelled, so the range never emitted 4 and 5 and never sent onComplete.
  • subscribe returns a Disposable. Disposing it after about 350 ms cancelled the interval after three ticks. An infinite source that is never disposed keeps running, and holding on to its Disposable is the way to stop it.

Creating sequences

Reactor has factory methods for every kind of source: fixed values, collections, ranges, generators with state, callback APIs and resources that must be closed. The program uses each one, with a small listener-based price feed standing in for a library that pushes events.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class Creating {

    // A callback-style API, as found in many libraries
    static class PriceFeed {
        private final List<Consumer<Double>> listeners = new ArrayList<>();

        void onPrice(Consumer<Double> listener) {
            listeners.add(listener);
        }

        void publish(double price) {
            listeners.forEach(l -> l.accept(price));
        }
    }

    public static void main(String[] args) {
        // From values and collections
        System.out.println("just:         " + Flux.just("a", "b", "c").collectList().block());
        System.out.println("fromIterable: " + Flux.fromIterable(List.of(3, 1, 2))
                .collectList().block());
        System.out.println("range(5, 3):  " + Flux.range(5, 3).collectList().block());

        // Mono from something that may be absent
        System.out.println("justOrEmpty(empty Optional) has a value: "
                + Mono.justOrEmpty(Optional.empty()).hasElement().block());

        // generate: synchronous, one element per call, with state (Fibonacci)
        Flux<Long> fib = Flux.generate(() -> new long[] {0, 1}, (s, sink) -> {
            sink.next(s[0]);
            long next = s[0] + s[1];
            s[0] = s[1];
            s[1] = next;
            return s;
        });
        System.out.println("generate, first 10 Fibonacci: " + fib.take(10).collectList().block());

        // create: bridge a listener API into a Flux
        PriceFeed feed = new PriceFeed();
        Flux<Double> prices = Flux.create(sink -> feed.onPrice(sink::next));
        List<Double> seen = new ArrayList<>();
        prices.subscribe(seen::add);
        feed.publish(101.5);
        feed.publish(102.25);
        System.out.println("create, from a listener: " + seen);

        // using: open a resource per subscription and always close it
        Flux<String> lines = Flux.using(
                () -> {
                    System.out.println("  resource opened");
                    return List.of("line 1", "line 2", "line 3").iterator();
                },
                it -> Flux.fromIterable(() -> it),
                it -> System.out.println("  resource closed"));
        System.out.println("using, take(2): " + lines.take(2).collectList().block());

        // error and empty are values too
        System.out.println("Flux.error, onErrorReturn: " + Flux.<String>error(
                new IllegalStateException("boom")).onErrorReturn("recovered").blockLast());
        System.out.println("Mono.empty().block(): " + Mono.empty().block());
    }
}

Output:

Output
just:         [a, b, c]
fromIterable: [3, 1, 2]
range(5, 3):  [5, 6, 7]
justOrEmpty(empty Optional) has a value: false
generate, first 10 Fibonacci: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
create, from a listener: [101.5, 102.25]
  resource opened
  resource closed
using, take(2): [line 1, line 2]
Flux.error, onErrorReturn: recovered
Mono.empty().block(): null
  • just, fromIterable and range emit known values. Mono.justOrEmpty turns an empty Optional into an empty Mono, so hasElement() was false.
  • generate calls its function once per requested element with a state object, here the last two Fibonacci numbers. It is pull-based, so take(10) stopped it after 10 values even though it is infinite.
  • create bridges push-based code: the listener calls sink.next whenever the feed publishes. Such a source ignores demand, which the next section shows the consequences of.
  • using opened its resource on subscription and closed it when the sequence ended, here early because of take(2). It is the reactive counterpart of try-with-resources.
  • Errors and emptiness are signals too. Mono.empty().block() returned null; use blockOptional() when emptiness is expected.

Backpressure and overflow strategies

A pull-based source such as range waits for requests. A push-based source created with Flux.create emits whenever the outside world produces, and needs a rule for values the subscriber has not asked for. The program pushes 1 to 10 at once into a subscriber that requests 3, and later 2 more, once for each OverflowStrategy.

Java
import java.util.ArrayList;
import java.util.List;
import org.reactivestreams.Subscription;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;

public class Backpressure {

    // A subscriber that asks for 3 elements, and 2 more later
    static final class Slow extends BaseSubscriber<Integer> {
        final List<Integer> got = new ArrayList<>();
        String end = "still open";

        @Override
        protected void hookOnSubscribe(Subscription s) {
            request(3);
        }

        @Override
        protected void hookOnNext(Integer v) {
            got.add(v);
        }

        @Override
        protected void hookOnError(Throwable e) {
            end = "error: " + e.getClass().getSimpleName();
        }

        @Override
        protected void hookOnComplete() {
            end = "complete";
        }
    }

    public static void main(String[] args) {
        // A push source that ignores demand: it emits 1..10 at once
        for (FluxSink.OverflowStrategy strategy : FluxSink.OverflowStrategy.values()) {
            Flux<Integer> burst = Flux.create(sink -> {
                for (int i = 1; i <= 10; i++) {
                    sink.next(i);
                }
                sink.complete();
            }, strategy);
            Slow s = new Slow();
            burst.subscribe(s);
            List<Integer> first = new ArrayList<>(s.got);
            s.request(2);                                   // later, the consumer asks for more
            System.out.printf("%-7s first %s, after request(2) %s, %s%n", strategy, first,
                    s.got.subList(first.size(), s.got.size()), s.end);
        }

        // A pull source respects demand, so nothing is lost or buffered
        Slow pulled = new Slow();
        Flux.range(1, 10).subscribe(pulled);
        System.out.println("range   first " + pulled.got + ", " + pulled.end
                + " (range waits for requests)");
    }
}

Output:

Output
IGNORE  first [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], after request(2) [], complete
ERROR   first [1, 2, 3], after request(2) [], error: OverflowException
DROP    first [1, 2, 3], after request(2) [], complete
LATEST  first [1, 2, 3], after request(2) [10], complete
BUFFER  first [1, 2, 3], after request(2) [4, 5], still open
range   first [1, 2, 3], still open (range waits for requests)
What each overflow strategy did with 10 values and a demand of 3, then 2
StrategyResultUse when
IGNOREAll 10 delivered despite a demand of 3; breaks the specificationAlmost never
ERROR3 delivered, then OverflowExceptionOverflow means a bug
DROP3 delivered, the other 7 thrown awayOld values are worthless, such as sensor readings
LATEST3 delivered, then only the newest, 10Only the current state matters, such as a price
BUFFER3 delivered, 4 and 5 on the next request, the rest keptEvery value matters and bursts are bounded; the default

BUFFER was still open at the end, holding 6 to 10 and the completion signal until more demand arrives. It is unbounded, so a source that is always faster than its consumer eventually exhausts memory. For other publishers, the operators onBackpressureBuffer(maxSize), onBackpressureDrop() and onBackpressureLatest() apply the same strategies anywhere in a pipeline.

Errors are signals

A reactive sequence ends with either a completion signal or an error signal, and an error ends it for good. The program parses the strings "1", "2", "x", "4", where "x" fails, and handles that failure in several ways, then adds a retry and a timeout.

Java
import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class Errors {

    public static void main(String[] args) {
        // An error ends the sequence: elements after it are never emitted
        Flux.just("1", "2", "x", "4")
                .map(Integer::parseInt)
                .subscribe(n -> System.out.println("got " + n),
                        e -> System.out.println("error signal: " + e.getClass().getSimpleName()),
                        () -> System.out.println("completed"));

        // onErrorResume switches to a fallback publisher
        System.out.println("onErrorResume: " + Flux.just("1", "2", "x", "4")
                .map(Integer::parseInt)
                .onErrorResume(e -> Flux.just(-1))
                .collectList().block());

        // onErrorContinue (use sparingly) drops the bad element and keeps going
        System.out.println("onErrorContinue: " + Flux.just("1", "2", "x", "4")
                .map(Integer::parseInt)
                .onErrorContinue((e, bad) -> System.out.println("  skipped " + bad))
                .collectList().block());

        // retry re-subscribes to the source: here it fails twice, then succeeds
        AtomicInteger attempts = new AtomicInteger();
        String result = Mono.fromCallable(() -> {
            int n = attempts.incrementAndGet();
            if (n < 3) {
                throw new IllegalStateException("attempt " + n + " failed");
            }
            return "ok on attempt " + n;
        }).retry(3).block();
        System.out.println("retry: " + result);

        // timeout turns a slow source into an error, which can then be handled
        String slow = Mono.just("late").delayElement(Duration.ofSeconds(2))
                .timeout(Duration.ofMillis(200))
                .onErrorReturn("fallback after timeout")
                .block();
        System.out.println("timeout: " + slow);
    }
}

Output:

Output
got 1
got 2
error signal: NumberFormatException
onErrorResume: [1, 2, -1]
  skipped x
onErrorContinue: [1, 2, 4]
retry: ok on attempt 3
timeout: fallback after timeout
  • With a plain subscribe, the error terminated the sequence: "4" was never parsed and "completed" never printed. Always pass an error handler to subscribe; without one, Reactor logs the error and drops it.
  • onErrorResume replaced the rest of the sequence with a fallback, here a single -1. onErrorReturn is the short form for one value, and onErrorMap translates the exception into another.
  • onErrorContinue skipped "x" and continued with 4. It only works with operators that support it and behaves surprisingly in complex pipelines, so the Reactor documentation recommends handling errors inside a flatMap instead.
  • retry(3) resubscribed after each failure, and the third attempt succeeded. Because retry resubscribes to the source, it only helps when the source is lazy, like fromCallable. For real services, retryWhen(Retry.backoff(...)) adds growing delays between attempts.
  • timeout turned a 2-second delay into an error after 200 ms, which onErrorReturn replaced with a default.

Cold, shared, cached and hot sources

Most publishers are cold: each subscriber gets its own independent run, for example its own HTTP call. Hot publishers emit regardless of subscribers, and late subscribers miss what was emitted earlier unless the publisher replays it. The program shows each kind.

Java
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;

public class ColdAndHot {

    public static void main(String[] args) throws Exception {
        // Cold: every subscriber triggers its own run of the source
        AtomicInteger runs = new AtomicInteger();
        Flux<String> cold = Flux.defer(() -> {
            runs.incrementAndGet();
            return Flux.just("a", "b");
        });
        cold.subscribe();
        cold.subscribe();
        System.out.println("cold source ran " + runs.get() + " times for 2 subscribers");

        // share(): one run of the source, multicast to current subscribers
        runs.set(0);
        Flux<Long> shared = Flux.defer(() -> {
            runs.incrementAndGet();
            return Flux.interval(Duration.ofMillis(100)).take(5);
        }).share();
        List<Long> first = new CopyOnWriteArrayList<>();
        List<Long> late = new CopyOnWriteArrayList<>();
        shared.subscribe(first::add);
        Thread.sleep(250);
        shared.subscribe(late::add);                         // joins while it is running
        Thread.sleep(500);
        System.out.println("shared source ran " + runs.get() + " time; first saw " + first
                + ", late subscriber saw " + late);

        // cache(): runs once and replays everything to later subscribers
        runs.set(0);
        Flux<String> cached = Flux.defer(() -> {
            runs.incrementAndGet();
            return Flux.just("x", "y");
        }).cache();
        System.out.println("cache(): first " + cached.collectList().block() + ", later "
                + cached.collectList().block() + ", source ran " + runs.get() + " time");

        // A Sink is a hot source you push values into from ordinary code
        Sinks.Many<String> events = Sinks.many().multicast().onBackpressureBuffer();
        List<String> received = new CopyOnWriteArrayList<>();
        events.asFlux().subscribe(received::add);
        events.tryEmitNext("login");
        events.tryEmitNext("click");
        events.tryEmitComplete();
        System.out.println("sink delivered: " + received);

        // A multicast sink does not replay: a subscriber that comes late sees only new values
        Sinks.Many<String> live = Sinks.many().multicast().directBestEffort();
        List<String> early = new CopyOnWriteArrayList<>();
        List<String> joinedLater = new CopyOnWriteArrayList<>();
        live.asFlux().subscribe(early::add);
        live.tryEmitNext("e1");
        live.asFlux().subscribe(joinedLater::add);
        live.tryEmitNext("e2");
        System.out.println("multicast: early " + early + ", joined later " + joinedLater);

        Sinks.Many<String> replay = Sinks.many().replay().limit(2);
        replay.tryEmitNext("r1");
        replay.tryEmitNext("r2");
        replay.tryEmitNext("r3");
        System.out.println("replay().limit(2), subscribing after 3 values: "
                + replay.asFlux().take(2).collectList().block());
    }
}

Output:

Output
cold source ran 2 times for 2 subscribers
shared source ran 1 time; first saw [0, 1, 2, 3, 4], late subscriber saw [2, 3, 4]
cache(): first [x, y], later [x, y], source ran 1 time
sink delivered: [login, click]
multicast: early [e1, e2], joined later [e2]
replay().limit(2), subscribing after 3 values: [r2, r3]
  • The cold source ran twice for two subscribers. If that source were a database query, it would be executed twice.
  • share() ran the source once and multicast it. The second subscriber joined after 250 ms, so it missed the values emitted at 100 and 200 ms and only saw 2, 3 and 4.
  • cache() also ran the source once, but replayed everything to the later subscriber. It suits expensive results that do not change, such as configuration loaded at startup; without a size or time limit it keeps every value forever.
  • A Sinks.Many bridges ordinary imperative code into a Flux: tryEmitNext pushes a value to every current subscriber. The multicast sink gave the late subscriber only "e2", while replay().limit(2) kept the last two values, "r2" and "r3", for anyone who subscribes later.

Choosing the right building block

Choosing a Reactor source or operator
NeedUse
A value computed per subscriberMono.fromSupplier or Mono.fromCallable, not Mono.just
A blocking call wrapped for laterMono.fromCallable plus subscribeOn; see schedulers
A sequence computed step by stepFlux.generate
A listener or callback APIFlux.create with a deliberate overflow strategy
Imperative code emitting eventsSinks.many(): multicast, unicast or replay
A resource that must be closedFlux.using
One run shared by current subscribersshare()
One run replayed to everyonecache(), ideally with a limit
Recover from errorsonErrorResume, onErrorReturn, retryWhen(Retry.backoff(...))
Stop an infinite sequenceKeep the Disposable and call dispose(), or use take

For transforming and combining sequences, continue with Reactor operators.