2

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

Gyan
  • 41
  • 1
  • 4

1 Answers1

4

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).
Brian Clozel
  • 56,583
  • 15
  • 167
  • 176