What Are the Mono and Flux Types?
In the context of reactive programming, particularly with the Project Reactor library in Java, Mono
and Flux
are two key types used to represent asynchronous sequences of data.
Mono
is a reactive type that represents a single value or an empty result. It can emit either one item or no item at all (i.e., it can complete without emitting any value).Mono<String> monoValue = Mono.just("Hello, World!");
Mono<String> emptyMono = Mono.empty();
Flux
is a reactive type that represents a sequence of 0 to N items. It can emit multiple values over time, and it can also complete without emitting any items.Flux<String> fluxValues = Flux.just("Item 1", "Item 2", "Item 3");
Flux<String> emptyFlux = Flux.empty();
Mono
can emit at most one item, while Flux
can emit zero or more items.Mono
is focused on a single result, whereas Flux
is designed for multiple results.Both Mono
and Flux
support a wide range of operators for transforming, filtering, and combining data, such as:
map()
: Transform the emitted items.filter()
: Filter emitted items based on a predicate.flatMap()
: Flatten nested structures or perform asynchronous operations.subscribe()
: Trigger the execution and handle the emitted items or errors.Here’s a simple example demonstrating both Mono
and Flux
:
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class ReactiveExample {
public static void main(String[] args) {
// Using Mono
Mono<String> monoExample = Mono.just("Single Value");
monoExample.subscribe(value -> System.out.println("Mono: " + value));
// Using Flux
Flux<String> fluxExample = Flux.just("Value 1", "Value 2", "Value 3");
fluxExample.subscribe(value -> System.out.println("Flux: " + value));
}
}
In this example, the Mono
emits a single value, while the Flux
emits multiple values. Both types are part of the reactive programming paradigm, allowing for non-blocking and asynchronous data processing.