Search code examples
javareactive-programmingproject-reactor

Do we really need doOnNext() if we have subscribe() already?


I am a beginner to reactive world of java and have one question which is do we need doOnNext(Consumer) when we already have a subscribe(Consumer) which does the same thing of consuming the publisher emitted events? In what cases its preferred to use one over the other?

doOnNext(Consumer<? super T> onNext)

subscribe(Consumer<? super T> consumer)

Solution

  • subscribe is a terminal operator, which means it triggers the whole flow and you can't add any other operator after that.

    doOnNext is an intermediate operator which means you can use it almost anywhere in the chain even multiple times. Unlike subscribe, it doesn't trigger the execution. It comes in handy when you are working with longer and more complex reactive streams. For example when you want to log at multiple stages of the pipeline.

    If we are considering only the side-effect part (basically the Consumer), then doOnNext is a more flexible approach.