flatmap and switchIfEmpty with Mono publisher
In this example, we write a simple program to explain the flatmap and switchIfEmpty with Mono publisher. Below we provide the example for your reference.
package com.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import reactor.core.publisher.Mono;
@SpringBootApplication
public class PublishersApplication {
public static void main(String[] args) {
SpringApplication.run(PublishersApplication.class, args);
Mono<String> msg = Mono.just("Hello Geeks");
msg.flatMap(msgs -> {
return Mono.just("Hello, " + msgs + "!");
}).switchIfEmpty(Mono.just("No data available")).subscribe(System.out::println);
}
}
- In the above program, first we create Mono publisher with String type and by using Mono.just().
- We provide the data to the publisher after this we use flatmap on Mono object, and this flatmap return a publisher.
- Immediately on flatmap we use switchIfEmpty operator. If publisher is empty the switchIfEmpty returns the No data available message other wise It returns Hello, Hello Geeks!
Output:
What are flatmap and switchifempty in Spring Reactive?
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 crucial roles in reactive programming. The reactive programming introduces a lot of operators to handle the business logic like flatmap, onErrorResume, map, zip, just, and other reactor operators. In this article, we explain what flatmap and switchIfEmpty.
Prerequisites:
To understand this content, you should know the topics below are easy to understand.
- Spring Framework
- Spring Reactor Programming
- Publisher and Consumer Concepts
- Event flow in Reactive Streams
- Operators in Spring Reactor
- Concept of Subscription
Contact Us