javaspringspring-webfluxproject-reactor

Difference between doOnComplete() and the third argument of subscribe() in Project Reactor


I’m currently working with Project Reactor and I’ve come across a scenario where I’m not sure whether to use doOnComplete() or the third argument of subscribe(). Both seem to be called when the Publisher emits a completion signal, but I suspect there are some differences between them.

Here’s a sample of the code I’m working with:

Flux.range(1, 10)
    .doOnComplete(() -> log.info("[Complete]"))
    .subscribe(
        data -> log.info("[data] : {}", data),
        error -> log.info("[error] : {}", error.getMessage()),
        () -> log.info("[Subscribe Complete]")
    );

In this code, both doOnComplete() and the third argument of subscribe() are logging a message when the stream is completed. However, I’m not sure when to use one over the other.

Thank you in advance for your help!


Solution

  • Both doOnComplete() and the third argument of subscribe() are used to perform actions when a Flux or Mono completes, but there are some differences in their use cases.

    1. doOnComplete(): doOnComplete() is an operator that allows you to perform a side effect (an action) when the sequence is completed successfully (i.e., without errors). It doesn't affect the termination signal itself; it's purely for side effects. It is often used for logging, resource cleanup, or any other action you want to take when the Flux or Mono completes successfully.

    2. Subscribe Callback (third argument of subscribe()): The third argument of the subscribe() method is a callback that is invoked when the sequence is completed, whether it completes with data or with an error. It is called after onNext() and onError() callbacks. It is suitable for actions that need to be taken after the whole sequence is completed, regardless of whether it completed with data or with an error.

    In your example, both doOnComplete() and the third argument of subscribe() are logging messages when the stream is completed. If you want to perform an action specifically when the sequence completes successfully, you can use doOnComplete(). If you want an action to be taken regardless of success or error, you can use the third argument of subscribe().