Mono and Flux in Spring WebFlux in Reactive APIs

πŸ“‘ Table of Contents

  1. Introduction to Mono and Flux
  2. Mono vs Flux: What’s the Difference?
  3. Creating Mono and Flux
  4. Common Operators (map, flatMap, filter, etc.)
  5. Handling Errors in Reactive Streams
  6. Practical Usage in Spring WebFlux APIs
  7. Final Thoughts
Mono and Flux in Spring WebFlux in Reactive APIs

πŸ”Ή 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.

TypeDescription
Mono0 or 1 item
Flux0 to N items (stream)

βš–οΈ 2. Mono vs Flux: What’s the Difference?

  • Mono is like Optional, but asynchronous.
  • Flux is 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.