1. Overview
In this article, we will learn how to check if mono is empty and perform an action accordingly.
A Flux object represents a reactive sequence of 0..N items, whereas a Mono object represents a single value or an empty (0..1) result.
You can compare Flux with a list and Mono with Optional. The Java optional
may or may not contain a non-null value. Similarly, Mono may contain a single value or empty. We will learn to perform an action when Mono is empty.
2. Mono example
Consider you have a database of customers with customerId
as the primary key. In the below code, we are using the customerRepository
to find a single customer from the database by using the customerId
. If the customer
exists, then it returns the customer
object. Otherwise, returns null
.
So the customerMono
object of type Mono<Customer>
contains either an customer
object (if exists in the database) otherwise null
.
@GetMapping(path = "/customers/{customerId}") public Mono<Customer> findCustomerById(@PathVariable String customerId) { Mono<Customer> customerMono = customerService.findById(customerId); return customerMono; }
2.1. Fallback to an alternative Mono if completes empty
At times, you want to fall back to an alternative Mono if the Mono is completed without any data. The switchIfEmpty
method is available to accomplish this.
For example, the following code first tries to use the customerService
to get the customer by using the customer id. If no customer is available and returned Mono is empty, then it falls back to the Mono specified in the switchIfEmpty
method.
@GetMapping(path = "/customers/{customerId}") public Mono<Customer> findCustomerById(@PathVariable String customerId) { Mono<Customer> customerMono = customerService.findById(customerId) .switchIfEmpty(backupService.findById(customerId)); return customerMono; }
2.2. Default value if mono is empty
If you want to provide a default value when the mono is completed without any data, then use defaultIfEmpty
method.
For example, the following code tries to fetch the customer
data from the database by using the customer id
. If the requested customer
id is not available in the database, we are returning 204 NO_CONTENT HTTP status as the result.
@GetMapping(path = "/customers/{customerId}") public Mono<ResponseEntity<Customer>> handleGetCustomer(@PathVariable String customerId) { Mono<ResponseEntity<Customer>> responseEntityMono = customerRepository .findById(customerId) .map(x -> new ResponseEntity<>(x, HttpStatus.OK)) .defaultIfEmpty(new ResponseEntity<>(HttpStatus.NO_CONTENT)); return responseEntityMono; }
3. Conclusion
To sum up, we have learned to check if Mono is empty and perform action.