Subscribe on Mono never executing

493 Views Asked by At

In the following sample (in Reactive Spring environment), "FIRST MONO EXECUTED" is never printed, while "SECOND MONO EXECUTED" is printed. Any idea why?

oAuth2AuthorizedClientService.loadAuthorizedClient(MYCLIENTID, MYPRINCIPALNAME)
        .subscribe(s -> System.out.println("FIRST MONO EXECUTED"));

Mono.just(new TokenResponse()).subscribe(s -> System.out.println("SECOND MONO EXECUTED"));

Where oAuth2AuthorizedClientService is an injected ReactiveOAuth2AuthorizedClientService bean.

I expect the first Mono to resolve.

1

There are 1 best solutions below

0
kerbermeister On

I think you can't see the result of your first publisher because the actual call inside loadAuthorizedClient is made in another thread, the execution is happening on it. When you call subscribe() on first publisher you immediately continue to execute your method, so you just making Mono.just() which is "literal", and subscribe to this mono, and it immediately prints you the result of your mono (because it is completed already) in your thread (without thread switching).

Assuming you're doing all of this in @Test, your test ends at this time and the first call loadAuthorizedClient is still executing, so you cannot see the result of your first publisher.

For testing purposes you can place Thread.sleep(n) just to wait some time for completion of your first publisher