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, and the idea that a blocking server dedicates one thread to each request. It also assumes you have read the chapter on the Reactive Streams contract. Here you learn the two types you will use in almost every WebFlux program.
Two publishers, two shapes
Project Reactor implements Reactive Streams with two Publisher types. Both are generic, and both describe work that has not necessarily happened yet.
| Type | Emits | Typical use |
|---|---|---|
| `Mono<T>` | 0 or 1 element, then completes or errors | Lookup by id, a single HTTP response, a save result |
| `Flux<T>` | 0 to N elements, then completes or errors | A list of rows, a stream of events, a paginated result |
The type tells the reader the cardinality. Mono<Book> means "at most one book". Flux<Book> means "any number of books". A Mono<Void> signals only completion, which suits operations such as a delete.
Creating them
You usually get a Mono or Flux from a library, such as a reactive repository or WebClient. You can also build them yourself with factory methods.
Mono<String> one = Mono.just("hello");
Mono<String> none = Mono.empty();
Mono<String> failed = Mono.error(new IllegalStateException("boom"));
Flux<Integer> numbers = Flux.range(1, 5);
Flux<String> letters = Flux.just("a", "b", "c");
Flux<Long> ticks = Flux.interval(java.time.Duration.ofSeconds(1));Mono.empty() is a normal outcome, not an error. It is how a lookup says "nothing found".
Nothing happens until you subscribe
A pipeline is a description of work. Building it does not run it. Execution starts when something subscribes.
import reactor.core.publisher.Flux;
public class OddSquares {
public static void main(String[] args) {
Flux<Integer> odds = Flux.range(1, 5)
.map(n -> n * n)
.filter(n -> n % 2 == 1);
System.out.println("Pipeline built, nothing printed yet");
odds.subscribe(System.out::println); // prints 1, 9, 25
}
}The program prints the "Pipeline built" line first, then 1, 9, and 25. Each operator such as map returns a new publisher that wraps the previous one. The squares of 1 to 5 are 1, 4, 9, 16, 25, and the filter keeps the odd ones.
In a WebFlux application you rarely call subscribe yourself. The framework subscribes when it writes the response. If your controller builds a pipeline but a stage in the middle drops it, for example by calling an operator and ignoring the returned value, nothing runs and no error appears.
Each subscription runs again
Most publishers are cold. Every subscriber triggers the source from the start.
import reactor.core.publisher.Flux;
public class ColdDemo {
public static void main(String[] args) {
Flux<Integer> source = Flux.range(1, 3)
.doOnNext(n -> System.out.println("producing " + n));
source.subscribe(n -> System.out.println("A got " + n));
source.subscribe(n -> System.out.println("B got " + n));
}
}Both subscribers see the full sequence, and "producing" prints six times. For an HTTP call this means two subscriptions send two requests. Keep that in mind before subscribing twice to the same WebClient pipeline.
Common errors
- Blocking to get the value. Calling
mono.block()inside a handler stalls an event-loop thread. Return theMonoand let the framework subscribe. - Returning
null. AMonocannot containnull. UseMono.empty()to represent absence.Mono.just(null)throws aNullPointerException. - Using
Fluxfor single values. PreferMonowhen at most one result is possible. It documents intent and avoids needless collection handling. - Forgetting that an error ends the sequence. After an error signal, a
Fluxemits nothing more.
Exercise
A controller method builds repository.findById(id).map(this::toDto); as a statement and then returns Mono.empty(). The database is never queried. Why?
Show answer
The built pipeline is never returned or subscribed to. Operators only describe work, and nothing runs until a subscriber appears. The method should return the pipeline, so the framework subscribes to it.
Exercise
Which type fits a method that returns all orders for a customer, and which fits one that deletes an order and reports only that it finished?
Show answer
Use Flux<Order> for all orders, since there can be zero or many. Use Mono<Void> for the delete, because it emits no element and only signals completion or error.