I am new to Spring webflux. Need to understand why Mono.switchIfEmpty operator is getting called even if data is not empty.
Sample Code:
public static void main(String[] args) {
Mono.just("test1")
.flatMap(val -> {
System.out.println("test2");
return Mono.just("test2");
})
.switchIfEmpty(method1())
.subscribe(s -> System.out.println(s));
}
private static Mono<String> method1() {
System.out.println("test3");
return Mono.empty();
}
Output
test3 test2 test2
With project reactor (and in reactive programming in general, to some extent), things happen in two stages:
Subscriber subscribes to itIn your case, calling method1 executes that method and your System.out.println is executed as expected.
If you want to see more in line with the pipeline execution, you could try:
private static Mono<String> method1() {
return Mono.defer(() -> {
System.out.println("test3");
return Mono.empty()
});
}
The Mono.defer operator will defer that operation until the pipeline is subscribed to.
There are better ways to achieve that though:
DoOnXYZ operators, which are meant for side-effect operations like thatlog() operator to get a better idea of what's happening here (subscription, backpressure, etc).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With