Java Reactive Programming — Flux and Mono
2 min readJul 23, 2023
Dependency :
What is Flux?
Flux is a standard Publisher that represents 0 to N asynchronous sequence values. This means that it can emit 0 to many values, possibly infinite values for onNext() requests, and then terminates with either a completion or an error signal.
Below are examples of the Flux demonstration.
public class Exercise2 {
public static Flux<String> stringNumbersFlux() {
return Flux.just("one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten")
.delayElements(Duration.ofSeconds(1));
}
public static Flux<Integer> intNumbersFlux() {
return Flux
.range(1, 10)
.delayElements(Duration.ofSeconds(1));
}
public static void main(String[] args) throws IOException {
// Use ReactiveSources.intNumbersFlux() and ReactiveSources.userFlux()
// Print all numbers in the ReactiveSources.intNumbersFlux stream
intNumbersFlux().subscribe(numbers -> System.out.println(numbers));
// Print all users in the ReactiveSources.stringNumbersFlux stream
stringNumbersFlux().subscribe(stringNumbers -> System.out.println(stringNumbers));
}
}
What is Mono?
Mono is a special type of Publisher. A Mono object represents a single or empty value. This means it can emit only one value at most for the onNext() request and then terminates with the onComplete() signal. In case of failure, it only emits a single onError() signal.
Below are examples of the Mono demonstration.
public class Exercise4 {
public static Mono<Integer> intNumberMono() {
return Mono.just(42)
.delayElement(Duration.ofSeconds(1));
}
public static void main(String[] args) throws IOException {
// Use ReactiveSources.intNumberMono()
// Print the value from intNumberMono when it emits
intNumberMono().subscribe(number -> System.out.println(number));
// Get the value from the Mono into an integer variable
Integer mono = ReactiveSources.intNumberMono().block();
System.out.println("Number : " + mono);
}
}