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.
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.FlowPublisherSubscriberSubscription
- The subscriber calls
, and the publisher answers withpublisher.subscribe(subscriber) .onSubscribe(subscription) - The subscriber calls
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.subscription.request(n) - The publisher sends up to n values with
, and ends with exactly oneonNext oronComplete , or stops when the subscriber callsonError .cancel()
Reactor adds two publisher types with hundreds of operators. Mono<T>OptionalFlux<T>mapfilter
| Type | Since | Values | Lazy | Asynchronous | Backpressure and cancellation |
|---|---|---|---|---|---|
java.util.stream.Stream | Java 8 | Many | Yes | No | No; the consumer pulls |
CompletableFuture | Java 8 | One | No; runs when created | Yes | Cancellation only |
java.util.concurrent.Flow | Java 9 | Many | Interfaces only | Yes | Yes, but no operators |
Mono | Reactor 3.0 | Zero or one | Yes | Optional | Yes |
Flux | Reactor 3.0 | Zero to infinite | Yes | Optional | Yes |
The programs on this page ran with Reactor 3.7 (reactor-core
Mono, Flux and laziness
A FluxMonoblock()collectList()
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:
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
had three even squares, from 2, 4 and 6, it cancelled the subscription and the range stopped. Demand and cancellation flow upstream.take(3) evaluates its argument once, when the Mono is created, so every subscriber gets the same timestamp.Mono.just(value) runs the code for each subscriber. Wrapping a slow or side-effecting call inMono.fromSupplier runs it immediately even if nobody ever subscribes, a common mistake.just emits on Reactor'sFlux.interval scheduler, not the main thread, andparallel waits for it. Blocking is fine in tests andblockLast() methods, but must not happen inside a reactive application's request handling.main
Watching the signals
The doOn...subscribe()BaseSubscriber
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:
--- 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
requested 9,223,372,036,854,775,807 elements,subscribe() , which the specification defines as "unbounded". All five values followed, thenLong.MAX_VALUE .onComplete - The custom subscriber requested 2 and received exactly 2. Its second
let one more through, and then it cancelled, so the range never emitted 4 and 5 and never sentrequest(2) .onComplete returns asubscribe . 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 itsDisposable is the way to stop it.Disposable
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.
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:
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 andfromIterable emit known values.range turns an emptyMono.justOrEmpty into an empty Mono, soOptional washasElement() .false calls its function once per requested element with a state object, here the last two Fibonacci numbers. It is pull-based, sogenerate stopped it after 10 values even though it is infinite.take(10) bridges push-based code: the listener callscreate whenever the feed publishes. Such a source ignores demand, which the next section shows the consequences of.sink.next opened its resource on subscription and closed it when the sequence ended, here early because ofusing . It is the reactive counterpart of try-with-resources.take(2)- Errors and emptiness are signals too.
returnedMono.empty().block() ; usenull when emptiness is expected.blockOptional()
Backpressure and overflow strategies
A pull-based source such as rangeFlux.createOverflowStrategy
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:
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)
| Strategy | Result | Use when |
|---|---|---|
IGNORE | All 10 delivered despite a demand of 3; breaks the specification | Almost never |
ERROR | 3 delivered, then OverflowException | Overflow means a bug |
DROP | 3 delivered, the other 7 thrown away | Old values are worthless, such as sensor readings |
LATEST | 3 delivered, then only the newest, 10 | Only the current state matters, such as a price |
BUFFER | 3 delivered, 4 and 5 on the next request, the rest kept | Every value matters and bursts are bounded; the default |
BUFFERonBackpressureBuffer(maxSize)onBackpressureDrop()onBackpressureLatest()
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.
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:
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
, the error terminated the sequence: "4" was never parsed and "completed" never printed. Always pass an error handler tosubscribe ; without one, Reactor logs the error and drops it.subscribe replaced the rest of the sequence with a fallback, here a single -1.onErrorResume is the short form for one value, andonErrorReturn translates the exception into another.onErrorMap 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 aonErrorContinue instead.flatMap resubscribed after each failure, and the third attempt succeeded. Because retry resubscribes to the source, it only helps when the source is lazy, likeretry(3) . For real services,fromCallable adds growing delays between attempts.retryWhen(Retry.backoff(...)) turned a 2-second delay into an error after 200 ms, whichtimeout replaced with a default.onErrorReturn
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.
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:
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.
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.share() 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.cache()- A
bridges ordinary imperative code into a Flux:Sinks.Many pushes a value to every current subscriber. The multicast sink gave the late subscriber only "e2", whiletryEmitNext kept the last two values, "r2" and "r3", for anyone who subscribes later.replay().limit(2)
Choosing the right building block
| Need | Use |
|---|---|
| A value computed per subscriber | Mono.fromSupplierMono.fromCallableMono.just |
| A blocking call wrapped for later | Mono.fromCallablesubscribeOn |
| A sequence computed step by step | Flux.generate |
| A listener or callback API | Flux.create |
| Imperative code emitting events | Sinks.many() |
| A resource that must be closed | Flux.using |
| One run shared by current subscribers | share() |
| One run replayed to everyone | cache() |
| Recover from errors | onErrorResumeonErrorReturnretryWhen(Retry.backoff(...)) |
| Stop an infinite sequence | Keep the Disposabledispose()take |
For transforming and combining sequences, continue with