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.

Similar Reads

Mono

Creation: A Mono can be created by using static methods like Mono.just() or Mono.empty() or Mono.error()Subscription: The subscriber subscribes to the Mono triggering the execution of the pipeline.Emission: The Mono publisher emits zero or one item followed by an onComplete or onError signalsOperators: Various operators can transform the emitted item, handle errors, or perform side-effects...

Flux

Creation: A Flux can be created by using static methods like Flux.just() or Flux.fromIterable() or Flux.range()Subscription: The subscriber subscribes to the Flux triggering the execution of the pipeline.Emission: The Mono publisher emits zero to N items followed by an onComplete or onError signalsOperators: Various operators can transform the emitted items, handle errors, buffer, window, or combine multiple Flux streams...

Examples of Mono and Flux

Here we provide two different examples for Mono and Flux publishers. The Mono publisher can emits zero or one and The Flux publisher can emits zero to N events....

Difference Between Mono and Flux

Below is the difference table of Mono and Flux....