π 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?
Mono
is likeOptional
, but asynchronous.Flux
is like a List, stream, or observable sequence.
Example:
1 2 3 4 5 |
Mono<String> nameMono = Mono.just("Ketan"); Flux<Integer> numberFlux = Flux.range(1, 5); |
π§ 3. Creating Mono and Flux
β Mono
1 2 3 4 5 |
Mono<String> emptyMono = Mono.empty(); Mono<String> valueMono = Mono.just("Hello Mono"); |
β Flux
1 2 3 4 5 |
Flux<String> stringFlux = Flux.just("Java", "Spring", "WebFlux"); Flux<Integer> rangeFlux = Flux.range(1, 10); |
π 4. Common Operators
Operators allow transformation and manipulation of the stream:
πΉ map
1 2 3 4 |
Flux<String> names = Flux.just("john", "doe").map(String::toUpperCase); |
πΉ flatMap
1 2 3 4 5 |
Flux<String> values = Flux.just("a", "b") .flatMap(val -> Mono.just(val.toUpperCase())); |
πΉ filter
1 2 3 4 5 |
Flux<Integer> evenNumbers = Flux.range(1, 10) .filter(i -> i % 2 == 0); |
πΉ zip
1 2 3 4 5 6 7 8 |
Flux<String> 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:
1 2 3 4 5 |
Mono<String> 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
1 2 3 4 5 6 7 8 9 10 11 12 |
@GetMapping("/product/{id}") public Mono<Product> getProduct(@PathVariable String id) { return repository.findById(id); } @GetMapping("/products") public Flux<Product> 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.