@GetMapping(path = "/customers/{customerId}")
public Mono<Customer> findCustomerById(@PathVariable String customerId) {
Mono<Customer> customerMono =
customerService.findById(customerId);
return customerMono;
2.1. Mono switchIfEmpty
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. Mono defaultIfEmpty
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 the differences between Mono switchIfEmpty vs defaultIfEmpty along with examples.