Difference Between Mono and Flux
Below is the difference table of Mono and Flux.
Aspect | Mono | Flux |
---|---|---|
Definition | Represents 0 or 1 item. | Represents 0 to N items. |
Use Cases | Single result. Ex: a database lookup for one record. | Multiple results. Ex: database query returning a list. |
Common Operations | map, flatMap, filter, then | map, flatMap, filter, take, skip, merge, zip |
Return Types | Mono<T> | Flux<T> |
Example 1 (Creating) | Mono.just(“Hello, Spring WebFlux!”) | Flux.just(“Item 1”, “Item 2”, “Item 3”) |
Example 2 (Handling HTTP Requests) | Mono<ServerResponse> handling single item response | Mono<ServerResponse> handling multiple item response |
Example 3 (REST Controller) | @GetMapping(“/single”) public Mono<String> getSingleItem() { return Mono.just(“Single Item”); } | @GetMapping(“/multiple”) public Flux<String> getMultipleItems() { return Flux.just(“Item 1”, “Item 2”, “Item 3”); } |
Publisher Type | Single-emission publisher | Multi-emission publisher |
Life cycle Events | onNext, onError, onComplete | onNext, onError, onComplete |
Reactive Stream Support | Backpressure handling | Backpressure handling |
Error Handling | onErrorReturn, onErrorResume, onErrorMap | onErrorReturn, onErrorResume, onErrorMap |
Cold Publisher | Emits items only when subscribed | Emits items only when subscribed |
Difference Between Mono and Flux in Spring WebFlux
Spring WebFlux is a part of the Spring Framework that provides reactive programming support for web applications. It introduces reactive types like Mono and Flux publishers which are fundamental to Its programming model. Mono and Flux play a crucial role in reactive programming.
In this article, we will explore Mono vs Flux.