π Table of Contents
- Introduction to Mono and Flux
- Mono vs Flux: Whatβs the Difference?
- Creating Mono and Flux
- Common Operators (
map,flatMap,filter, etc.) - Handling Errors in Reactive Streams
- Practical Usage in Spring WebFlux APIs
- Final Thoughts

πΉ 1. Introduction to Mono and Flux
Mono and Flux are core types in Project Reactor, the library used in Spring WebFlux. These types are used to model asynchronous and non-blocking data sequences.
| Type | Description |
|---|---|
| Mono | 0 or 1 item |
| Flux | 0 to N items (stream) |
βοΈ 2. Mono vs Flux: Whatβs the Difference?
Monois likeOptional, but asynchronous.Fluxis like a List, stream, or observable sequence.
Example:
Mono nameMono = Mono.just("Ketan");
Flux numberFlux = Flux.range(1, 5);
π§ 3. Creating Mono and Flux
β Mono
Mono emptyMono = Mono.empty();
Mono valueMono = Mono.just("Hello Mono");
β Flux
Flux stringFlux = Flux.just("Java", "Spring", "WebFlux");
Flux rangeFlux = Flux.range(1, 10);
π 4. Common Operators
Operators allow transformation and manipulation of the stream:
πΉ map
Flux names = Flux.just("john", "doe").map(String::toUpperCase);
πΉ flatMap
Flux values = Flux.just("a", "b")
.flatMap(val -> Mono.just(val.toUpperCase()));
πΉ filter
Flux evenNumbers = Flux.range(1, 10)
.filter(i -> i % 2 == 0);
πΉ zip
Flux zipped = Flux.zip(
Flux.just("A", "B"),
Flux.just("1", "2"),
(first, second) -> first + second
);
β 5. Handling Errors in Reactive Streams
Use .onErrorResume(), .onErrorReturn(), and .doOnError().
Example:
Mono errorHandled = Mono.error(new RuntimeException("Oops"))
.onErrorResume(e -> Mono.just("Fallback value"));
π 6. Practical Usage in Spring WebFlux
In Spring WebFlux, controller methods return Mono<T> or Flux<T>.
π¦ Sample Controller
@GetMapping("/product/{id}")
public Mono getProduct(@PathVariable String id) {
return repository.findById(id);
}
@GetMapping("/products")
public Flux getAllProducts() {
return repository.findAll();
}
These return types allow Spring WebFlux to handle requests reactively and efficiently, without blocking threads.
β 7. Final Thoughts
Understanding how to work with Mono and Flux in Spring WebFlux is essential for reactive programming in Spring Boot. They are powerful tools for modeling asynchronous data pipelines and building non-blocking APIs.