0

I want to understand why the timeout handler is invoked in below code. Since, I had configured the timeout of 100 seconds, I wasn't expecting the handler to be invoked as the element was being emitted after 1 second.

public static void main(String[] args) throws InterruptedException {
    Mono<Integer> integerMono = Mono.just(1).delayElement(Duration.ofSeconds(1));

    integerMono
     .timeout(Duration.ofSeconds(100),handler())
     .subscribe(integer -> System.out.println(integer));

    Thread.sleep(10000);
  }

  private static Mono<? extends Integer> handler() {
    System.out.println("handler invoked");
    return Mono.just(10);
  }

below is the output :

handler invoked
1

can someone please explain, why it's behaving so, and how do we achieve the expected behaviour?

Martin Tarjányi
  • 8,863
  • 2
  • 31
  • 49
Rahul Gupta
  • 1,079
  • 2
  • 15
  • 27

1 Answers1

2

Your handler() method is invoked every time you call it. It's a simple Java method that creates Mono object. But this Mono will be subscribed only after timeout.

You can change your handler method like this to test it:

private Mono<? extends Integer> handler() {
    System.out.println("Handler assembling");
    return Mono.just(10)
            .doOnSubscribe(subscription ->
                    System.out.println("Handler subscribed"));
}

There is a blog post about assembly and subscription differences.

That SO answer could be helpful too.

Alexander Pankin
  • 3,787
  • 1
  • 13
  • 23