When I execute the below code (Junit) only the last sys out gets printed, i.e Subscribetest. Can someone please explain why the sysouts in doOnSubscribe, doOnSuccess, doOnNext are not getting printed/executed.
@Test
public void doOns(){
Mono<String> mono = Mono.just("test");
mono.doOnSubscribe(s -> System.out.println("Just got subscribed" +s ))
.doOnSuccess(s -> System.out.println("I am successfull" + s))
.doOnNext(s -> System.out.println("next next next" + s));
mono.subscribe(s -> System.out.println("Subscribe" + s));
}
This is because you are actually breaking the chain. You see nothing happens before you subscribe, but you need to keep the chain intact.
What you are doing is that you are first initializing your Mono
.
then you are declaring a reactive flow.
And then on the last line, you are actually subscribing to the original Mono
and not the reactive flow that you expect.
This is what it should look like.
// Here you declare your mono
Mono<String> mono = Mono.just("test");
// Here you add operators which will return
//a new Mono with your operators attached
Mono<String> stringMono = mono.doOnSubscribe(s -> System.out.println("Just got subscribed" + s))
.doOnNext(s -> System.out.println("next next next" + s))
.doOnSuccess(s -> System.out.println("I am successfull" + s));
// Subscribe to the new Mono
stringMono.subscribe(s -> System.out.println("Subscribe " + s));
or with a bit of simplification.
Mono.just("test")
.doOnSubscribe(s -> System.out.println("Just got subscribed " + s))
.doOnNext(s -> System.out.println("next next next " + s))
.doOnSuccess(s -> System.out.println("I am successfull " + s))
.subscribe(s -> System.out.println("Subscribe " + s));
Output:
Just got subscribed reactor.core.publisher.Operators$ScalarSubscription@5524cca1
next next next test
I am successfull test
Subscribe test