Class UnicastProcessor<T>

  • Type Parameters:
    T - the value type received and emitted by this Processor subclass
    All Implemented Interfaces:
    FlowableSubscriber<T>, org.reactivestreams.Processor<T,​T>, org.reactivestreams.Publisher<T>, org.reactivestreams.Subscriber<T>

    public final class UnicastProcessor<@NonNull T>
    extends FlowableProcessor<T>
    A FlowableProcessor variant that queues up events until a single Subscriber subscribes to it, replays those events to it until the Subscriber catches up and then switches to relaying events live to this single Subscriber until this UnicastProcessor terminates or the Subscriber cancels its subscription.

    This processor does not have a public constructor by design; a new empty instance of this UnicastProcessor can be created via the following create methods that allow specifying the retention policy for items:

    • create() - creates an empty, unbounded UnicastProcessor that caches all items and the terminal event it receives.
    • create(int) - creates an empty, unbounded UnicastProcessor with a hint about how many total items one expects to retain.
    • create(boolean) - creates an empty, unbounded UnicastProcessor that optionally delays an error it receives and replays it after the regular items have been emitted.
    • create(int, Runnable) - creates an empty, unbounded UnicastProcessor with a hint about how many total items one expects to retain and a callback that will be called exactly once when the UnicastProcessor gets terminated or the single Subscriber cancels.
    • create(int, Runnable, boolean) - creates an empty, unbounded UnicastProcessor with a hint about how many total items one expects to retain and a callback that will be called exactly once when the UnicastProcessor gets terminated or the single Subscriber cancels and optionally delays an error it receives and replays it after the regular items have been emitted.

    If more than one Subscriber attempts to subscribe to this Processor, they will receive an IllegalStateException if this UnicastProcessor hasn't terminated yet, or the Subscribers receive the terminal event (error or completion) if this Processor has terminated.

    The UnicastProcessor buffers notifications and replays them to the single Subscriber as requested, for which it holds upstream items an unbounded internal buffer until they can be emitted.

    Since a UnicastProcessor is a Reactive Streams Processor, nulls are not allowed (Rule 2.13) as parameters to onNext(Object) and onError(Throwable). Such calls will result in a NullPointerException being thrown and the processor's state is not changed.

    Since a UnicastProcessor is a Flowable as well as a FlowableProcessor, it honors the downstream backpressure but consumes an upstream source in an unbounded manner (requesting Long.MAX_VALUE).

    When this UnicastProcessor is terminated via onError(Throwable) the current or late single Subscriber may receive the Throwable before any available items could be emitted. To make sure an onError event is delivered to the Subscriber after the normal items, create a UnicastProcessor with the create(boolean) or create(int, Runnable, boolean) factory methods.

    Even though UnicastProcessor implements the Subscriber interface, calling onSubscribe is not required (Rule 2.12) if the processor is used as a standalone source. However, calling onSubscribe after the UnicastProcessor reached its terminal state will result in the given Subscription being canceled immediately.

    Calling onNext(Object), onError(Throwable) and onComplete() is required to be serialized (called from the same thread or called non-overlappingly from different threads through external means of serialization). The FlowableProcessor.toSerialized() method available to all FlowableProcessors provides such serialization and also protects against reentrance (i.e., when a downstream Subscriber consuming this processor also wants to call onNext(Object) on this processor recursively).

    This UnicastProcessor supports the standard state-peeking methods hasComplete(), hasThrowable(), getThrowable() and hasSubscribers().

    Backpressure:
    UnicastProcessor honors the downstream backpressure but consumes an upstream source (if any) in an unbounded manner (requesting Long.MAX_VALUE).
    Scheduler:
    UnicastProcessor does not operate by default on a particular Scheduler and the single Subscriber gets notified on the thread the respective onXXX methods were invoked.
    Error handling:
    When the onError(Throwable) is called, the UnicastProcessor enters into a terminal state and emits the same Throwable instance to the current single Subscriber. During this emission, if the single Subscribers cancels its respective Subscriptions, the Throwable is delivered to the global error handler via RxJavaPlugins.onError(Throwable). If there were no Subscribers subscribed to this UnicastProcessor when the onError() was called, the global error handler is not invoked.

    Example usage:

    
     UnicastProcessor<Integer> processor = UnicastProcessor.create();
    
     TestSubscriber<Integer> ts1 = processor.test();
    
     // fresh UnicastProcessors are empty
     ts1.assertEmpty();
    
     TestSubscriber<Integer> ts2 = processor.test();
    
     // A UnicastProcessor only allows one Subscriber during its lifetime
     ts2.assertFailure(IllegalStateException.class);
    
     processor.onNext(1);
     ts1.assertValue(1);
    
     processor.onNext(2);
     ts1.assertValues(1, 2);
    
     processor.onComplete();
     ts1.assertResult(1, 2);
    
     // ----------------------------------------------------
    
     UnicastProcessor<Integer> processor2 = UnicastProcessor.create();
    
     // a UnicastProcessor caches events until its single Subscriber subscribes
     processor2.onNext(1);
     processor2.onNext(2);
     processor2.onComplete();
    
     TestSubscriber<Integer> ts3 = processor2.test();
    
     // the cached events are emitted in order
     ts3.assertResult(1, 2);
     
    Since:
    2.0
    • Field Detail

      • onTerminate

        final java.util.concurrent.atomic.AtomicReference<java.lang.Runnable> onTerminate
      • delayError

        final boolean delayError
      • done

        volatile boolean done
      • error

        java.lang.Throwable error
      • downstream

        final java.util.concurrent.atomic.AtomicReference<org.reactivestreams.Subscriber<? super T>> downstream
      • cancelled

        volatile boolean cancelled
      • once

        final java.util.concurrent.atomic.AtomicBoolean once
      • requested

        final java.util.concurrent.atomic.AtomicLong requested
      • enableOperatorFusion

        boolean enableOperatorFusion
    • Constructor Detail

      • UnicastProcessor

        UnicastProcessor​(int capacityHint,
                         java.lang.Runnable onTerminate,
                         boolean delayError)
        Creates an UnicastProcessor with the given capacity hint and callback for when the Processor is terminated normally or its single Subscriber cancels.

        History: 2.0.8 - experimental

        Parameters:
        capacityHint - the capacity hint for the internal, unbounded queue
        onTerminate - the callback to run when the Processor is terminated or cancelled, null not allowed
        delayError - deliver pending onNext events before onError
        Since:
        2.2
    • Method Detail

      • create

        @CheckReturnValue
        @NonNull
        public static <T> @NonNull UnicastProcessor<T> create​(int capacityHint)
        Creates an UnicastProcessor with the given internal buffer capacity hint.
        Type Parameters:
        T - the value type
        Parameters:
        capacityHint - the hint to size the internal unbounded buffer
        Returns:
        an UnicastProcessor instance
        Throws:
        java.lang.IllegalArgumentException - if capacityHint is non-positive
      • create

        @CheckReturnValue
        @NonNull
        public static <T> @NonNull UnicastProcessor<T> create​(boolean delayError)
        Creates an UnicastProcessor with default internal buffer capacity hint and delay error flag.

        History: 2.0.8 - experimental

        Type Parameters:
        T - the value type
        Parameters:
        delayError - deliver pending onNext events before onError
        Returns:
        an UnicastProcessor instance
        Since:
        2.2
      • create

        @CheckReturnValue
        @NonNull
        public static <T> @NonNull UnicastProcessor<T> create​(int capacityHint,
                                                              @NonNull
                                                              @NonNull java.lang.Runnable onTerminate)
        Creates an UnicastProcessor with the given internal buffer capacity hint and a callback for the case when the single Subscriber cancels its subscription or the processor is terminated.

        The callback, if not null, is called exactly once and non-overlapped with any active replay.

        Type Parameters:
        T - the value type
        Parameters:
        capacityHint - the hint to size the internal unbounded buffer
        onTerminate - the non null callback
        Returns:
        an UnicastProcessor instance
        Throws:
        java.lang.NullPointerException - if onTerminate is null
        java.lang.IllegalArgumentException - if capacityHint is non-positive
      • create

        @CheckReturnValue
        @NonNull
        public static <T> @NonNull UnicastProcessor<T> create​(int capacityHint,
                                                              @NonNull
                                                              @NonNull java.lang.Runnable onTerminate,
                                                              boolean delayError)
        Creates an UnicastProcessor with the given internal buffer capacity hint, delay error flag and a callback for the case when the single Subscriber cancels its subscription or the processor is terminated.

        The callback, if not null, is called exactly once and non-overlapped with any active replay.

        History: 2.0.8 - experimental

        Type Parameters:
        T - the value type
        Parameters:
        capacityHint - the hint to size the internal unbounded buffer
        onTerminate - the non null callback
        delayError - deliver pending onNext events before onError
        Returns:
        an UnicastProcessor instance
        Throws:
        java.lang.NullPointerException - if onTerminate is null
        java.lang.IllegalArgumentException - if capacityHint is non-positive
        Since:
        2.2
      • doTerminate

        void doTerminate()
      • drainRegular

        void drainRegular​(org.reactivestreams.Subscriber<? super @NonNull T> a)
      • drainFused

        void drainFused​(org.reactivestreams.Subscriber<? super @NonNull T> a)
      • drain

        void drain()
      • onSubscribe

        public void onSubscribe​(org.reactivestreams.Subscription s)
        Description copied from interface: FlowableSubscriber
        Implementors of this method should make sure everything that needs to be visible in Subscriber.onNext(Object) is established before calling Subscription.request(long). In practice this means no initialization should happen after the request() call and additional behavior is thread safe in respect to onNext.
      • onNext

        public void onNext​(@NonNull T t)
      • onError

        public void onError​(java.lang.Throwable t)
      • onComplete

        public void onComplete()
      • subscribeActual

        protected void subscribeActual​(org.reactivestreams.Subscriber<? super @NonNull T> s)
        Description copied from class: Flowable
        Operator implementations (both source and intermediate) should implement this method that performs the necessary business logic and handles the incoming Subscribers.

        There is no need to call any of the plugin hooks on the current Flowable instance or the Subscriber; all hooks and basic safeguards have been applied by Flowable.subscribe(Subscriber) before this method gets called.

        Specified by:
        subscribeActual in class Flowable<T>
        Parameters:
        s - the incoming Subscriber, never null
      • getThrowable

        @Nullable
        @CheckReturnValue
        public @Nullable java.lang.Throwable getThrowable()
        Description copied from class: FlowableProcessor
        Returns the error that caused the FlowableProcessor to terminate or null if the FlowableProcessor hasn't terminated yet.

        The method is thread-safe.

        Specified by:
        getThrowable in class FlowableProcessor<T>
        Returns:
        the error that caused the FlowableProcessor to terminate or null if the FlowableProcessor hasn't terminated yet