Reactor Mono and Flux
What you will learn
Reactor Mono represents zero or one item; Flux represents zero or more. They describe pipelines that may be subscribed to later. Operators transform, combine or recover signals, not ordinary values. A cold sequence starts its work per subscriber; a hot source may emit independently of a particular subscription.
- Choose Mono or Flux for a result cardinality.
- Explain deferred work and ordered asynchronous mapping.
- Separate empty completion from error and cancellation.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. Reactor and WebFlux examples require the companion Maven project. Their predicted results are not execution evidence.
Model eager versus deferred work
public class Main {
public static void main(String[] args) {var calls = new java.util.concurrent.atomic.AtomicInteger(); int captured = calls.incrementAndGet(); java.util.function.Supplier<Integer> deferred = calls::incrementAndGet; System.out.println(captured + ":" + captured); System.out.println(deferred.get() + ":" + deferred.get()); }}Expected output:
1:12:3The supplier is a plain-Java model of deferred work; it is not a Reactor subscription.
Assembly and subscription
Mono.just(value) captures an already computed value at assembly. Mono.defer creates a publisher per subscription; fromCallable defers a callable. A cold sequence can repeat a side effect on each subscription or retry. Hot sources may omit earlier values for late subscribers; replay/cache changes sharing, retention and error behavior. map performs a synchronous transformation; flatMap maps to publishers and may interleave results; concatMap subscribes in order. Bound flatMap concurrency and prefetch rather than assuming defaults fit the service.
Error and absence
Empty completes without a value, not with null. Reactor cannot emit null; use justOrEmpty or a deliberate empty result. switchIfEmpty handles absence, onErrorResume handles matching errors by subscribing to a replacement sequence. Errors terminate the upstream sequence; recovery does not restart at the failing item. Retry resubscribes and can repeat effects: restrict to transient, safe operations and finite attempts. No retry example here performs external work.
Model absence without swallowing failures
public class Main { static java.util.Optional<Integer> stock(String sku) { if(sku.equals("broken")) throw new IllegalStateException("unavailable"); return sku.equals("B1") ? java.util.Optional.of(5) : java.util.Optional.empty(); } public static void main(String[] args) {System.out.println(stock("missing").orElse(0)); try { stock("broken"); } catch(IllegalStateException e) { System.out.println("failure"); } }}Expected output:
0failureOptional models cardinality only. It does not model asynchronous error signaling.
Compose and defer
Source-reviewed, NOT RUN. File lab-fixtures/reactive-v45/src/test/java/lab/PipelineTest.java; use the companion lab README.
package lab;import java.time.Duration;import java.util.concurrent.atomic.AtomicInteger;import org.junit.jupiter.api.Test;import reactor.core.publisher.Flux;import reactor.core.publisher.Mono;import reactor.test.StepVerifier;import static org.junit.jupiter.api.Assertions.assertEquals;class PipelineTest { @Test void transform() { var result = Flux.just(1, 2, 3, 4).filter(n -> n % 2 == 0) .concatMap(n -> Mono.just(n * 10)); StepVerifier.create(result).expectNext(20, 40).expectComplete() .verify(Duration.ofSeconds(2)); } @Test void laziness() { var calls = new AtomicInteger(); var value = Mono.defer(() -> Mono.just(calls.incrementAndGet())); assertEquals(0, calls.get()); StepVerifier.create(value).expectNext(1).expectComplete().verify(Duration.ofSeconds(2)); StepVerifier.create(value).expectNext(2).expectComplete().verify(Duration.ofSeconds(2)); }}Predicted behavior: 20, 40; separate subscriptions produce 1 and 2.
concatMap preserves sequential subscription order; defer moves creation to each subscription.
Handle empty and typed errors
Source-reviewed, NOT RUN. File lab-fixtures/reactive-v45/src/test/java/lab/RecoveryTest.java; use the companion lab README.
package lab;import java.time.Duration;import org.junit.jupiter.api.Test;import reactor.core.publisher.Mono;import reactor.test.StepVerifier;class RecoveryTest { @Test void emptyIsNotFailure() { StepVerifier.create(Mono.<Integer>empty().switchIfEmpty(Mono.just(0))) .expectNext(0).expectComplete().verify(Duration.ofSeconds(2)); } @Test void typedRecovery() { StepVerifier.create(Mono.<Integer>error(new IllegalArgumentException("bad")) .onErrorResume(IllegalStateException.class, e -> Mono.just(0))) .expectError(IllegalArgumentException.class).verify(Duration.ofSeconds(2)); }}Predicted behavior: Empty becomes 0; IllegalArgumentException remains an error.
Fallback should represent intended domain absence, not mask every failure.
Common mistakes
Do not call subscribe inside map or use block to extract a value inside a reactive chain. Returning Mono from map creates a nested publisher; use flatMap for a dependent Mono. Do not treat retry as free or turn every failure into empty.
Practice
Use a Supplier<Integer> and an AtomicInteger initialized to 10. Create the supplier without invoking it, print the counter, invoke it twice and print both results.
Expected output:
101112Compare with the manual review criteria.
Official reading: Reactor · StepVerifier · Boot BOM. Reactor and WebFlux execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Reactor Mono and Flux — knowledge check
Reactive programming reasoning.
Which result cardinality fits Mono?
What happens with Mono.just(expensive())?
Which mapping keeps inner subscriptions sequential?
Which handles an empty completion?
What risk does retry introduce?