11

I have this confusion, when does doOnNext is triggered before or after of element emission by Publisher (Flux/Mono).

dvsakgec
  • 3,514
  • 4
  • 28
  • 35
  • 1
    Since `doOnNext` provides you the element flowing through the pipeline with a `Consumer`, it is after. Order is something like this: source emits item -> doOnNext lambda is triggered -> subscriber onNext is called: https://github.com/reactor/reactor-core/blob/master/reactor-core/src/main/java/reactor/core/publisher/FluxPeek.java#L167-L193 – Martin Tarjányi Jul 25 '19 at 15:27

2 Answers2

22

It's after the publication of the element - and it has to be after by definition, otherwise the Consumer passed to doOnNext wouldn't have access to the element emitted.

However, doOnNext() is called before the subscriber. For example:

Flux.just("first", "second")
        .doOnNext(x -> System.out.println(x + " onNext"))
        .subscribe(System.out::println);

...would output:

first onNext
first
second onNext
second
Michael Berry
  • 70,193
  • 21
  • 157
  • 216
8

I am afraid you haven't understood reactive properly, and that's perfectly fine :). In Rx, the subscription goes bottom-up. Consider the following code:

Flux<Integer> f = Flux.fromIterable(Arrays.asList(1,2,3));

Since there is no subscriber, nothing happens. No item would be emitted. Now consider this:

f.subscribe(System.out::println)

What happens is that the subscriber subscribes to the flux, and items are emitted.

Now consider this:

f.doOnNext(System.out::println).subscribe(System.out.println);

Remember, the subscription happens in a bottom-up manner. So over here, the subscriber subscribes to the doOnNext(), and the doOnNext() subscribes to the original flux, which then starts emitting events. doOnNext() then intercepts each event and performs some side-effect.

Prashant Pandey
  • 4,332
  • 3
  • 26
  • 44
  • Prashant, I admit that I am still trying to get my head around the reactive stuff. Though the question from a requirement where I need to execute something just before publisher starts working to produce data. – dvsakgec Jul 29 '19 at 06:55