flatmap and switchIfEmpty with Flux publisher
In this example, we write a simple program to explain the flatmap and switchIfEmpty with Flux 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.Flux;
import reactor.core.publisher.Mono;
@SpringBootApplication
public class PublishersApplication {
public static void main(String[] args) {
SpringApplication.run(PublishersApplication.class, args);
Flux<String> names = Flux.just("John", "Marry", "Micky", "Hani");
names.flatMap(name -> {
return Mono.just("Hello, " + name + "!");
}).switchIfEmpty(Mono.just("No names available")).subscribe(System.out::println);
}
}
- In the above program, first we create Flux publisher with String type and by using Flux.just().
- We provide the data to the publisher after this we use flatmap on Flux object, and this flatmap return a publisher.
- Immediately on flatmap we use switchIfEmpty operator. If publisher is empty the switchIfEmpty returns the No names available message and then prints each names to the console.
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