Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring WebFlux Mono.switchIfEmpty is getting called even if data present

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

like image 378
Gyan Avatar asked Dec 03 '25 14:12

Gyan


1 Answers

With project reactor (and in reactive programming in general, to some extent), things happen in two stages:

  1. Setting up the reactive pipeline
  2. The actual execution of that pipeline as soon as a Subscriber subscribes to it

In 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:

  • you could use one of the many DoOnXYZ operators, which are meant for side-effect operations like that
  • you could use the log() operator to get a better idea of what's happening here (subscription, backpressure, etc).
like image 93
Brian Clozel Avatar answered Dec 05 '25 13:12

Brian Clozel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!