Talk about the doOn method of reactive streamsspublisher.

  reactive-programming

Order

This article mainly studies the doOn method of reactive streams Publisher.

DoOn series method

Let’s take Flux as an example.
reactor-core-3.1.2.RELEASE-sources.jar! /reactor/core/publisher/Flux.java

doOnSubscribe

/**
     * Add behavior (side-effect) triggered when the {@link Flux} is subscribed.
     * <p>
     * <img class="marble" src="https://raw.githubusercontent.com/reactor/reactor-core/v3.1.1.RELEASE/src/docs/marble/doonsubscribe.png" alt="">
     * <p>
     * @param onSubscribe the callback to call on {@link Subscriber#onSubscribe}
     *
     * @return an observed  {@link Flux}
     */
    public final Flux<T> doOnSubscribe(Consumer<? super Subscription> onSubscribe) {
        Objects.requireNonNull(onSubscribe, "onSubscribe");
        return doOnSignal(this, onSubscribe, null, null, null, null, null, null);
    }

doOnRequest

/**
     * Add behavior (side-effect) triggering a {@link LongConsumer} when this {@link Flux}
     * receives any request.
     * <p>
     *     Note that non fatal error raised in the callback will not be propagated and
     *     will simply trigger {@link Operators#onOperatorError(Throwable, Context)}.
     *
     * <p>
     * <img class="marble" src="https://raw.githubusercontent.com/reactor/reactor-core/v3.1.1.RELEASE/src/docs/marble/doonrequest.png" alt="">
     *
     * @param consumer the consumer to invoke on each request
     *
     * @return an observed  {@link Flux}
     */
    public final Flux<T> doOnRequest(LongConsumer consumer) {
        Objects.requireNonNull(consumer, "consumer");
        return doOnSignal(this, null, null, null, null, null, consumer, null);
    }

doOnNext

/**
     * Add behavior (side-effect) triggered when the {@link Flux} emits an item.
     * <p>
     * <img class="marble" src="https://raw.githubusercontent.com/reactor/reactor-core/v3.1.1.RELEASE/src/docs/marble/doonnext.png" alt="">
     * <p>
     * @param onNext the callback to call on {@link Subscriber#onNext}
     *
     * @return an observed  {@link Flux}
     */
    public final Flux<T> doOnNext(Consumer<? super T> onNext) {
        Objects.requireNonNull(onNext, "onNext");
        return doOnSignal(this, null, onNext, null, null, null, null, null);
    }

doOnError

/**
     * Add behavior (side-effect) triggered when the {@link Flux} completes with an error.
     * <p>
     * <img class="marble" src="https://raw.githubusercontent.com/reactor/reactor-core/v3.1.1.RELEASE/src/docs/marble/doonerror.png" alt="">
     * <p>
     * @param onError the callback to call on {@link Subscriber#onError}
     *
     * @return an observed  {@link Flux}
     */
    public final Flux<T> doOnError(Consumer<? super Throwable> onError) {
        Objects.requireNonNull(onError, "onError");
        return doOnSignal(this, null, null, onError, null, null, null, null);
    }

doOnEach

/**
     * Add behavior (side-effects) triggered when the {@link Flux} emits an item, fails with an error
     * or completes successfully. All these events are represented as a {@link Signal}
     * that is passed to the side-effect callback. Note that this is an advanced operator,
     * typically used for monitoring of a Flux.
     *
     * @param signalConsumer the mandatory callback to call on
     *   {@link Subscriber#onNext(Object)}, {@link Subscriber#onError(Throwable)} and
     *   {@link Subscriber#onComplete()}
     * @return an observed {@link Flux}
     * @see #doOnNext(Consumer)
     * @see #doOnError(Consumer)
     * @see #doOnComplete(Runnable)
     * @see #materialize()
     * @see Signal
     */
    public final Flux<T> doOnEach(Consumer<? super Signal<T>> signalConsumer) {
        return onAssembly(new FluxDoOnEach<>(this, signalConsumer));
    }

doOnComplete

/**
     * Add behavior (side-effect) triggered when the {@link Flux} completes successfully.
     * <p>
     * <img class="marble" src="https://raw.githubusercontent.com/reactor/reactor-core/v3.1.1.RELEASE/src/docs/marble/dooncomplete.png" alt="">
     * <p>
     * @param onComplete the callback to call on {@link Subscriber#onComplete}
     *
     * @return an observed  {@link Flux}
     */
    public final Flux<T> doOnComplete(Runnable onComplete) {
        Objects.requireNonNull(onComplete, "onComplete");
        return doOnSignal(this, null, null, null, onComplete, null, null, null);
    }

doOnCancel

/**
     * Add behavior (side-effect) triggered when the {@link Flux} is cancelled.
     * <p>
     * <img class="marble" src="https://raw.githubusercontent.com/reactor/reactor-core/v3.1.1.RELEASE/src/docs/marble/dooncancel.png" alt="">
     * <p>
     * @param onCancel the callback to call on {@link Subscription#cancel}
     *
     * @return an observed  {@link Flux}
     */
    public final Flux<T> doOnCancel(Runnable onCancel) {
        Objects.requireNonNull(onCancel, "onCancel");
        return doOnSignal(this, null, null, null, null, null, null, onCancel);
    }

doOnTerminate

/**
     * Add behavior (side-effect) triggered when the {@link Flux} terminates, either by
     * completing successfully or with an error.
     * <p>
     * <img class="marble" src="https://raw.githubusercontent.com/reactor/reactor-core/v3.1.1.RELEASE/src/docs/marble/doonterminate.png" alt="">
     * <p>
     * @param onTerminate the callback to call on {@link Subscriber#onComplete} or {@link Subscriber#onError}
     *
     * @return an observed  {@link Flux}
     */
    public final Flux<T> doOnTerminate(Runnable onTerminate) {
        Objects.requireNonNull(onTerminate, "onTerminate");
        return doOnSignal(this,
                null,
                null,
                e -> onTerminate.run(),
                onTerminate,
                null,
                null,
                null);
    }

doOnSignal

    @SuppressWarnings("unchecked")
    static <T> Flux<T> doOnSignal(Flux<T> source,
            @Nullable Consumer<? super Subscription> onSubscribe,
            @Nullable Consumer<? super T> onNext,
            @Nullable Consumer<? super Throwable> onError,
            @Nullable Runnable onComplete,
            @Nullable Runnable onAfterTerminate,
            @Nullable LongConsumer onRequest,
            @Nullable Runnable onCancel) {
        if (source instanceof Fuseable) {
            return onAssembly(new FluxPeekFuseable<>(source,
                    onSubscribe,
                    onNext,
                    onError,
                    onComplete,
                    onAfterTerminate,
                    onRequest,
                    onCancel));
        }
        return onAssembly(new FluxPeek<>(source,
                onSubscribe,
                onNext,
                onError,
                onComplete,
                onAfterTerminate,
                onRequest,
                onCancel));
    }

Example

static class DemoSubsriber implements Subscriber<Integer>{

        static final Logger LOGGER = LoggerFactory.getLogger(DemoSubsriber.class);

        @Override
        public void onSubscribe(Subscription s) {
            LOGGER.info("request max");
            s.request(Integer.MAX_VALUE);
        }

        @Override
        public void onNext(Integer integer) {
            LOGGER.info("get data:{}",integer);

        }

        @Override
        public void onError(Throwable t) {

        }

        @Override
        public void onComplete() {
            LOGGER.info("onComplete");
        }
    }

    @Test
    public void testDoOnMethods(){
        Flux.range(1, 3)
//                .log()
                .doOnSubscribe(e -> LOGGER.info("doOnSubscribe:{}",e))
                .doOnEach(e -> LOGGER.info("doOnEach:{}",e))
                .doOnError(e -> LOGGER.info("doOnError:{}",e))
                .doOnNext(e -> LOGGER.info("doOnNext:{}",e))
                .doOnRequest(e -> LOGGER.info("doOnRequest:{}",e))
                .doOnTerminate(new Runnable() {
                    @Override
                    public void run() {
                        LOGGER.info("doOnTerminate");
                    }
                })
                .doOnCancel(new Runnable() {
                    @Override
                    public void run() {
                        LOGGER.info("doOnCancel");
                    }
                })
                .doOnComplete(new Runnable() {
                    @Override
                    public void run() {
                        LOGGER.info("doOnComplete");
                    }
                })
                .subscribe(new DemoSubsriber());

    }

Output

23:14:16.837 [main] DEBUG reactor.util.Loggers$LoggerFactory - Using Slf4j logging framework
23:14:16.850 [main] INFO com.example.demo.FluxTest - doOnSubscribe:reactor.core.publisher.FluxRange$RangeSubscription@20398b7c
23:14:16.852 [main] INFO com.example.demo.FluxTest$DemoSubsriber - request max
23:14:16.852 [main] INFO com.example.demo.FluxTest - doOnRequest:2147483647
23:14:16.852 [main] INFO com.example.demo.FluxTest - doOnEach:reactor.core.publisher.FluxDoOnEach$DoOnEachSubscriber@2286778
23:14:16.852 [main] INFO com.example.demo.FluxTest - doOnNext:1
23:14:16.852 [main] INFO com.example.demo.FluxTest$DemoSubsriber - get data:1
23:14:16.852 [main] INFO com.example.demo.FluxTest - doOnEach:reactor.core.publisher.FluxDoOnEach$DoOnEachSubscriber@2286778
23:14:16.852 [main] INFO com.example.demo.FluxTest - doOnNext:2
23:14:16.852 [main] INFO com.example.demo.FluxTest$DemoSubsriber - get data:2
23:14:16.852 [main] INFO com.example.demo.FluxTest - doOnEach:reactor.core.publisher.FluxDoOnEach$DoOnEachSubscriber@2286778
23:14:16.852 [main] INFO com.example.demo.FluxTest - doOnNext:3
23:14:16.852 [main] INFO com.example.demo.FluxTest$DemoSubsriber - get data:3
23:14:16.853 [main] INFO com.example.demo.FluxTest - doOnEach:onComplete()
23:14:16.853 [main] INFO com.example.demo.FluxTest - doOnTerminate
23:14:16.853 [main] INFO com.example.demo.FluxTest - doOnComplete
23:14:16.856 [main] INFO com.example.demo.FluxTest$DemoSubsriber - onComplete

Summary

DoOn series method is publisher’s synchronous hook method, which is triggered when subscriber triggers a series of events.

doc