Project Reactor Basics — Mono<T> and Flux<T>
- coding z2m
- Jul 1
- 2 min read
🔹 Mono<T> and Flux<T> — the core types of Project Reactor. These are the reactive building blocks in Spring WebFlux, WebClient, and Reactive MongoDB. 🔹 What is Mono<T>?
🧾 Think of Mono as:
A container for 0 or 1 item — like an optional result.
✅ Use Cases:
Getting a single record from DB
Reading 1 file
Getting a REST API response
Representing empty result or error Mono<String> monoName = Mono.just("Alice"); ✅ Emits "Alice" → then completes ❌ Empty Mono: Mono<String> emptyMono = Mono.empty(); Emits nothing → completes 🔹 What is Flux<T>?
🧾 Think of Flux as:
A stream of 0 to many items — like a List but asynchronous & lazy.
✅ Use Cases:
Fetching all users from DB
Reading a stream of events (e.g., IoT data)
Returning streamed response from server
Implementing Server-Sent Events / WebSockets
Flux<String> fluxFruits = Flux.just("Apple", "Banana", "Orange");
✅ Emits each item → then completes
🧠 Mono vs Flux in Summary
Feature | Mono<T> | Flux<T> |
Emits | 0 or 1 item | 0 to many items |
Similar to | Optional / Future | List / Stream |
Example | User by ID | All users |
Terminal behavior | Completes or Errors | Emits, then completes or errors |
Use in WebFlux | Mono<User> in GET /users/1 | Flux<User> in GET /users |
🔄 Life Cycle of Mono / Flux [Subscribed] → [onNext(data)] → [onComplete()]
↘
[onError(e)]
onNext() → emits data
onComplete() → signals completion
onError() → signals error ✅ Hands-On Example
Let’s write a small Java example using both: import reactor.core.publisher.Mono;
import reactor.core.publisher.Flux;
public class ReactorBasics {
public static void main(String[] args) {
// --- Mono ---
Mono<String> userMono = Mono.just("Alice");
userMono.subscribe(
name -> System.out.println("User: " + name),
error -> System.err.println("Error: " + error),
() -> System.out.println("Mono Completed")
);
// --- Flux ---
Flux<String> fruitFlux = Flux.just("Apple", "Banana", "Mango");
fruitFlux.subscribe(
fruit -> System.out.println("Fruit: " + fruit),
error -> System.err.println("Error: " + error),
() -> System.out.println("Flux Completed")
);
}
} 🖨 Output User: Alice
Mono Completed
Fruit: Apple
Fruit: Banana
Fruit: Mango
Flux Completed 💡 Important Notes:
Nothing happens until subscribe() is called.
Mono/Flux are cold by default → they only emit when subscribed.
In Spring Boot, subscribe() is handled by the framework automatically (when returning from controllers). ❓ Q: When would you use Mono instead of Flux?
Use Mono when:
You expect a single result
You’re making a blocking call replacement
E.g., fetching user by ID, creating one record, calling a third-party API
🎯 You Now Understand:
✅ Core Reactor Type | Meaning |
Mono<T> | 0 or 1 item |
Flux<T> | 0 to many items |
subscribe() | Starts the flow |
Streams are lazy | No data until subscribed |
Comments