Sub topic 3
Mono and Flux: zero-or-one and zero-to-many results
This chapter assumes you know Java lambdas and generics, basic Spring Boot (beans, dependency injection, @RestController), HTTP and REST, and the thread-per-request model. It also assumes you have read the previous chapter on the Reactive Streams contract: a Publisher emits signals to a Subscriber, and a Subscription links them.
Why Reactor has two types
Project Reactor is the reactive library that Spring WebFlux builds on. It implements the Reactive Streams Publisher interface twice, with two types that differ in how many elements they can emit.
Mono<T>emits zero or one element, then completes or fails.Flux<T>emits zero to many elements, then completes or fails. AFluxcan also be infinite.
The split is about intent. A method that returns Mono<User> tells the reader that at most one user comes back. A method that returns Flux<User> tells the reader that there may be many. A single Publisher<User> would hide that difference. It would also hide which operators make sense, because "take the first element" means little for a Mono.
| Question | `Mono<T>` | `Flux<T>` |
|---|---|---|
| How many elements? | 0 or 1 | 0 to N, possibly unbounded |
| Typical source | Find by id, one HTTP response | List query, event stream, ticks |
| Blocking equivalent | `Optional<T>` or `T` | `List<T>` or `Stream<T>` |
| Ends with | `onComplete` or `onError` | `onComplete` or `onError` |
Both types are lazy. Creating one does not start any work. Work starts only when something subscribes.
The signals a publisher can send
A subscriber receives these signals, always in this order:
onSubscribe, once, which hands over theSubscription.onNext, zero or more times, once per element.- Exactly one terminal signal:
onCompleteoronError. After a terminal signal, nothing else is sent.
A Mono sends at most one onNext. An empty Mono goes straight to onComplete. This matters because "no result" is a normal outcome in reactive code, not a null and not an error.
Creating a Mono
The factory methods you will use most often:
import reactor.core.publisher.Mono;
public class MonoFactories {
public static void main(String[] args) {
Mono<String> hello = Mono.just("hello"); // one known value
Mono<String> nothing = Mono.empty(); // completes with no value
Mono<String> failed = Mono.error(new IllegalStateException("boom"));
Mono<String> deferred = Mono.fromSupplier(() -> "computed later");
hello.subscribe(System.out::println); // hello
nothing.subscribe(
v -> System.out.println("never printed"),
e -> System.out.println("never printed"),
() -> System.out.println("empty completed")); // empty completed
failed.subscribe(
v -> System.out.println("never printed"),
e -> System.out.println("error: " + e.getMessage())); // error: boom
deferred.subscribe(System.out::println); // computed later
}
}Note that Mono.just(value) rejects null with a NullPointerException. Reactive Streams forbids null elements. Use Mono.justOrEmpty(value) when the value may be null, or an Optional.
Creating a Flux
import reactor.core.publisher.Flux;
import java.util.List;
public class FluxFactories {
public static void main(String[] args) {
Flux<String> letters = Flux.just("a", "b", "c");
Flux<Integer> numbers = Flux.range(1, 3);
Flux<String> fromList = Flux.fromIterable(List.of("x", "y"));
Flux<String> none = Flux.empty();
letters.subscribe(System.out::println); // a b c, one per line
numbers.subscribe(System.out::println); // 1 2 3
fromList.subscribe(System.out::println); // x y
none.subscribe(System.out::println); // prints nothing
}
}Flux.interval(Duration) creates an infinite Flux<Long> that emits a counter on a timer. You will use it later for streaming responses.
Nothing happens until you subscribe
This is the most common source of confusion for people coming from blocking code. Building a pipeline only describes it. Consider the pipeline from the plan for this tutorial:
Flux<Integer> odds = Flux.range(1, 5)
.map(n -> n * n)
.filter(n -> n % 2 == 1);
odds.subscribe(System.out::println); // prints 1, 9, 25The first statement does no computing. It returns a new Flux that wraps the previous one. The call to subscribe triggers the work: range emits 1 to 5, map squares each number, filter keeps the odd squares, and the lambda passed to subscribe prints them.
Two consequences follow.
- A method that returns a
MonoorFluxbut never has its result subscribed does nothing. A call such asrepository.save(book);on a reactive repository, with the result ignored, never writes to the database. - Subscribing twice runs the pipeline twice. Each subscriber gets its own run of a cold publisher.
import reactor.core.publisher.Mono;
import java.util.concurrent.atomic.AtomicInteger;
public class ColdDemo {
public static void main(String[] args) {
AtomicInteger calls = new AtomicInteger();
Mono<Integer> counted = Mono.fromSupplier(calls::incrementAndGet);
counted.subscribe(v -> System.out.println("first: " + v)); // first: 1
counted.subscribe(v -> System.out.println("second: " + v)); // second: 2
}
}The supplier ran once per subscription. If you want to share one result among subscribers, use cache() on a Mono, or share() or publish().autoConnect() on a Flux. These are advanced tools. Reach for them only when you have a real reason.
Who subscribes in a WebFlux application
In a WebFlux controller you almost never call subscribe yourself. You return the Mono or Flux, and the framework subscribes when it is ready to write the response. This is why an annotated controller can simply return Mono<Book>. The next chapters use that.
Calling subscribe() inside a handler is usually a bug. The subscription runs detached from the request, so errors are lost and the response may be sent before the work finishes. Return the publisher instead, and chain further work with operators.
Subscribing with callbacks
subscribe has overloads that take lambdas for each signal:
import reactor.core.publisher.Flux;
public class SubscribeOverloads {
public static void main(String[] args) {
Flux.just(1, 2, 3)
.map(n -> {
if (n == 3) throw new IllegalArgumentException("three is not allowed");
return n * 10;
})
.subscribe(
value -> System.out.println("next: " + value),
error -> System.out.println("error: " + error.getMessage()),
() -> System.out.println("complete"));
}
}This prints next: 10, next: 20, then error: three is not allowed. The complete line never prints, because an error is a terminal signal. A thrown exception inside map is caught by Reactor and converted into onError. It does not propagate as a normal Java exception through the call stack.
If you pass no error handler, Reactor reports the exception through Operators.onErrorDropped or throws an ErrorCallbackNotImplemented exception. Always provide an error path in code that subscribes directly.
Converting between Mono and Flux
The two types convert in both directions.
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.List;
public class Conversions {
public static void main(String[] args) {
Flux<Integer> numbers = Flux.range(1, 4);
Mono<List<Integer>> asList = numbers.collectList(); // Flux -> Mono of a List
Mono<Integer> first = numbers.next(); // first element only
Mono<Long> count = numbers.count(); // number of elements
Mono<Integer> sum = numbers.reduce(0, Integer::sum); // fold into one value
Flux<Integer> single = Mono.just(7).flux(); // Mono -> Flux of one
asList.subscribe(System.out::println); // [1, 2, 3, 4]
first.subscribe(System.out::println); // 1
count.subscribe(System.out::println); // 4
sum.subscribe(System.out::println); // 10
single.subscribe(System.out::println); // 7
}
}Be careful with collectList() on a large or infinite Flux. It buffers every element in memory and, for an infinite source, never completes. A later chapter on streaming explains when to keep data as a Flux instead.
Do not block to get the value out
Both types offer block(), which waits for the result and returns it. Reactor throws an IllegalStateException if you call it on a thread that must not block, such as a Netty event-loop thread. Even where it is allowed, block() gives up the benefit of the non-blocking model by tying up a thread. Use it in main methods, simple scripts, and tests, but not in request-handling code.
import reactor.core.publisher.Mono;
public class BlockOk {
public static void main(String[] args) {
String value = Mono.just("ok").map(String::toUpperCase).block();
System.out.println(value); // OK
}
}Common errors
- Forgetting to subscribe or return. A pipeline whose result is discarded never runs. If a side effect "does not happen," check that the publisher is returned or subscribed.
- Returning
nullfrom a lambda.map(x -> null)fails with aNullPointerException. Return an empty publisher throughflatMapinstead, or wrap withOptional. - Treating empty as an error. An empty
Monocompletes normally. A controller returning an emptyMonoproduces an empty200response unless you addswitchIfEmpty. - Doing expensive work eagerly.
Mono.just(expensiveCall())runsexpensiveCall()immediately, while the pipeline is being built. UseMono.fromSupplier(() -> expensiveCall())orMono.deferso the work happens at subscription time. - Mixing up
Mono<List<T>>andFlux<T>. The first emits one list after the whole result is ready. The second emits elements one at a time. For a REST list endpoint,Flux<T>is usually the right return type, because it lets the framework write elements as they arrive.
Summary of the model
A Mono or Flux is a recipe, not a result. It describes work that may produce zero, one, or many values, followed by completion or an error. Subscribing runs the recipe. In a WebFlux application the framework subscribes for you, so your job is to build the recipe correctly and return it.
Exercise
A method contains the line Mono.fromSupplier(() -> counter.incrementAndGet()); and its result is never used. After the method runs, what is the value of counter, and why? Then say what one change would make the counter increase.
Show answer
The counter stays at its initial value. A Mono is lazy, and with no subscriber the supplier never runs. To make it increase, subscribe to the Mono (for example with .subscribe()), or return it so that the framework or caller subscribes. Subscribing twice would increase the counter twice, because each subscription reruns the supplier.
Exercise
You need an endpoint that returns all books, and another that returns one book by id or nothing if it is missing. Which of Mono and Flux fits each, and what happens in the second case if the id is not found and you add no extra operator?
Show answer
The list endpoint returns Flux<Book>, since it emits zero to many books. The lookup returns Mono<Book>, since it emits zero or one. If the id is not found, the Mono is empty and completes without a value, so the response is an empty body with a success status rather than a 404. Adding switchIfEmpty(Mono.error(...)) turns that into a 404.