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:

πŸ”§ 3. Creating Mono and Flux

βœ… Mono

βœ… Flux

πŸ”„ 4. Common Operators

Operators allow transformation and manipulation of the stream:

πŸ”Ή map

πŸ”Ή flatMap

πŸ”Ή filter

πŸ”Ή zip

❌ 5. Handling Errors in Reactive Streams

Use .onErrorResume(), .onErrorReturn(), and .doOnError().

Example:

🌐 6. Practical Usage in Spring WebFlux

In Spring WebFlux, controller methods return Mono<T> or Flux<T>.

πŸ“¦ Sample Controller

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.