0

My understanding is that when a Mono is subscribed to the first signal is doOnNext then doOnSuccess and then doOnTerminate however when I run the below code the sequence of execution of these methods is the sequence in which they have been chained, i.e doOnTerminate, doOnSuccess, doOnNext. If I change the sequence of chaining the sequence also get changed.

@Test
public void doOnsMono(){
    Mono<String> mono = Mono.just("ABC");
    mono.doOnSubscribe(s -> System.out.println("Just got subscribed") )
            .doOnTerminate(() -> System.out.println("Termination happens at the end"))
            .doOnSuccess(s -> System.out.println("I am successfull " + s))
            .doOnNext(s -> System.out.println("next next next" + s))
            .subscribe(s -> System.out.println("Subscribe" + s));

}

Output is such Just got subscribed

Termination happens at the end

I am successfull ABC

next next nextABC

SubscribeABC

Can someone please explain this behavior or the gap in my understanding.

lkatiforis
  • 5,703
  • 2
  • 16
  • 35

2 Answers2

1

Your publisher:

Mono.just("ABC")

emits an element("ABC") and completes. All three methods are triggered simultaneously there is no order of execution. Check this answer to understand the purpose of each method and how they differ.

lkatiforis
  • 5,703
  • 2
  • 16
  • 35
  • Thanks for directing. So, if I understand correctly which method gets called depends on what's in the Mono and whether it completes successfully. As for sequence in which they are called, that has nothing to do with a "lifecycle" of mono as such and get triggered based on chaining sequence. – Ankit Ghildiyal Aug 30 '22 at 20:00
  • 1
    @AnkitGhildiyal Exactly. – lkatiforis Aug 30 '22 at 20:25
0

Having gone through the link shared by @Ikatoforis and running the test examples there here's what I have deduced (same thing I posted in comment) Which method gets called depends on what's in the Mono and whether it completes successfully. As for sequence in which they are called, that has nothing to do with a "lifecycle" of mono as such and get triggered based on chaining sequence.