Top Description Inners Fields Constructors Methods
io.reactivex.rxjava3.processors

public final Class BehaviorProcessor<T>

extends FlowableProcessor<T>
Class Inheritance
Type Parameters
<T>
the type of item expected to be observed and emitted by the Processor
Imports
java.util.Objects, java.util.concurrent.atomic.*, java.util.concurrent.locks.*, org.reactivestreams.*, io.reactivex.rxjava3.annotations.*, io.reactivex.rxjava3.exceptions.MissingBackpressureException, io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper, io.reactivex.rxjava3.internal.util.*, .AppendOnlyLinkedArrayList.NonThrowingPredicate, io.reactivex.rxjava3.plugins.RxJavaPlugins

Processor that emits the most recent item it has observed and all subsequent observed items to each subscribed Subscriber.

This processor does not have a public constructor by design; a new empty instance of this BehaviorProcessor can be created via the create() method and a new non-empty instance can be created via createDefault(Object) (named as such to avoid overload resolution conflict with Flowable.create that creates a Flowable, not a BehaviorProcessor).

In accordance with the Reactive Streams specification (Rule 2.13) nulls are not allowed as default initial values in createDefault(Object) or as parameters to onNext(Object) and onError(Throwable).

When this BehaviorProcessor is terminated via onError(Throwable) or onComplete(), the last observed item (if any) is cleared and late org.reactivestreams.Subscribers only receive the respective terminal event.

The BehaviorProcessor does not support clearing its cached value (to appear empty again), however, the effect can be achieved by using a special item and making sure Subscribers subscribe through a filter whose predicate filters out this special item:


BehaviorProcessor<Integer> processor = BehaviorProcessor.create();

final Integer EMPTY = Integer.MIN_VALUE;

Flowable<Integer> flowable = processor.filter(v -> v != EMPTY);

TestSubscriber<Integer> ts1 = flowable.test();

processor.onNext(1);
// this will "clear" the cache
processor.onNext(EMPTY);

TestSubscriber<Integer> ts2 = flowable.test();

processor.onNext(2);
processor.onComplete();

// ts1 received both non-empty items
ts1.assertResult(1, 2);

// ts2 received only 2 even though the current item was EMPTY
// when it got subscribed
ts2.assertResult(2);

// Subscribers coming after the processor was terminated receive
// no items and only the onComplete event in this case.
flowable.test().assertResult();

Even though BehaviorProcessor 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 BehaviorProcessor reached its terminal state will result in the given Subscription being cancelled immediately.

Calling onNext(Object), offer(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 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). Note that serializing over offer(Object) is not supported through toSerialized() because it is a method available on the PublishProcessor and BehaviorProcessor classes only.

This BehaviorProcessor supports the standard state-peeking methods hasComplete(), hasThrowable(), getThrowable() and hasSubscribers() as well as means to read the latest observed value in a non-blocking and thread-safe manner via hasValue() or getValue().

Note that this processor signals MissingBackpressureException if a particular Subscriber is not ready to receive onNext events. To avoid this exception being signaled, use offer(Object) to only try to emit an item when all Subscribers have requested item(s).

Backpressure:
The BehaviorProcessor does not coordinate requests of its downstream Subscribers and expects each individual Subscriber is ready to receive onNext items when onNext(Object) is called. If a Subscriber is not ready, a MissingBackpressureException is signalled to it. To avoid overflowing the current Subscribers, the conditional offer(Object) method is available that returns true if any of the Subscribers is not ready to receive onNext events. If there are no Subscribers to the processor, offer() always succeeds. If the BehaviorProcessor is (optionally) subscribed to another Publisher, this upstream Publisher is consumed in an unbounded fashion (requesting Long#MAX_VALUE).
Scheduler:
BehaviorProcessor does not operate by default on a particular io.reactivex.rxjava3.core.Scheduler and the Subscribers get notified on the thread the respective onXXX methods were invoked.
Error handling:
When the onError(Throwable) is called, the BehaviorProcessor enters into a terminal state and emits the same Throwable instance to the last set of Subscribers. During this emission, if one or more Subscribers cancel their respective Subscriptions, the Throwable is delivered to the global error handler via io.reactivex.rxjava3.plugins.RxJavaPlugins#onError(Throwable) (multiple times if multiple Subscribers cancel at once). If there were no Subscribers subscribed to this BehaviorProcessor when the onError() was called, the global error handler is not invoked.

Example usage:

 // subscriber will receive all events.
 BehaviorProcessor<Object> processor = BehaviorProcessor.create("default");
 processor.subscribe(subscriber);
 processor.onNext("one");
 processor.onNext("two");
 processor.onNext("three");

 // subscriber will receive the "one", "two" and "three" events, but not "zero"
 BehaviorProcessor<Object> processor = BehaviorProcessor.create("default");
 processor.onNext("zero");
 processor.onNext("one");
 processor.subscribe(subscriber);
 processor.onNext("two");
 processor.onNext("three");

 // subscriber will receive only onComplete
 BehaviorProcessor<Object> processor = BehaviorProcessor.create("default");
 processor.onNext("zero");
 processor.onNext("one");
 processor.onComplete();
 processor.subscribe(subscriber);

 // subscriber will receive only onError
 BehaviorProcessor<Object> processor = BehaviorProcessor.create("default");
 processor.onNext("zero");
 processor.onNext("one");
 processor.onError(new RuntimeException("error"));
 processor.subscribe(subscriber);
  

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static class

Field Summary

Modifier and TypeField and Description
pack-priv static final BehaviorProcessor.BehaviorSubscription<T>[]
pack-priv static final Object[]
pack-priv long
pack-priv final ReadWriteLock
pack-priv final Lock
pack-priv final AtomicReference<BehaviorProcessor.BehaviorSubscription<T>[]>
pack-priv final AtomicReference<Throwable>
pack-priv static final BehaviorProcessor.BehaviorSubscription<T>[]
pack-priv final AtomicReference<Object>
pack-priv final Lock

Constructor Summary

AccessConstructor and Description
pack-priv
BehaviorProcessor()

Constructs an empty BehaviorProcessor.

pack-priv
BehaviorProcessor(T
the initial value, not null (verified)
defaultValue
)

Constructs a BehaviorProcessor with the given initial value.

Method Summary

Modifier and TypeMethod and Description
pack-priv boolean
public static <
the type of item the BehaviorProcessor will emit
T
>
@NonNull BehaviorProcessor<T>

Returns:

the constructed BehaviorProcessor
create
()

Creates a BehaviorProcessor without a default item.

public static <
the type of item the BehaviorProcessor will emit
T
>
@NonNull BehaviorProcessor<T>

Returns:

the constructed BehaviorProcessor
createDefault
(T
the item that will be emitted first to any Subscriber as long as the BehaviorProcessor has not yet observed any items from its source Observable
defaultValue
)

Creates a BehaviorProcessor that emits the last item it observed and all subsequent items to each Subscriber that subscribes to it.

public @Nullable Throwable
getThrowable()

Implements abstract io.reactivex.rxjava3.processors.FlowableProcessor.getThrowable.

Returns the error that caused the FlowableProcessor to terminate or null if the FlowableProcessor hasn't terminated yet.
public T

Returns:

a single value the BehaviorProcessor currently has or null if no such value exists
getValue
()

Returns a single value the BehaviorProcessor currently has or null if no such value exists.

public boolean
hasComplete()

Implements abstract io.reactivex.rxjava3.processors.FlowableProcessor.hasComplete.

Returns true if the FlowableProcessor has reached a terminal state through a complete event.
public boolean
hasSubscribers()

Implements abstract io.reactivex.rxjava3.processors.FlowableProcessor.hasSubscribers.

Returns true if the FlowableProcessor has subscribers.
public boolean
hasThrowable()

Implements abstract io.reactivex.rxjava3.processors.FlowableProcessor.hasThrowable.

Returns true if the FlowableProcessor has reached a terminal state through an error event.
public boolean

Returns:

true if the BehaviorProcessor has any value
hasValue
()

Returns true if the BehaviorProcessor has any value.

public boolean

Returns:

true if the item was emitted to all Subscribers
offer
(T
the item to emit, not null
t
)

Tries to emit the item to all currently subscribed Subscribers if all of them has requested some value, returns false otherwise.

public void
onComplete()

Implements org.reactivestreams.Subscriber.onComplete.

Successful terminal state.
public void
onError(@NonNull Throwable
the throwable signaled
t
)

Implements org.reactivestreams.Subscriber.onError.

Failed terminal state.
public void
onNext(T
the element signaled
t
)

Implements org.reactivestreams.Subscriber.onNext.

Data notification sent by the Publisher in response to requests to Subscription#request(long).
public void
pack-priv void
pack-priv void
protected void
pack-priv int
pack-priv BehaviorProcessor.BehaviorSubscription<T>[]
terminate(Object terminalValue)

Inherited from io.reactivex.rxjava3.processors.FlowableProcessor:
toSerialized

Field Detail

EMPTYback to summary
pack-priv static final BehaviorProcessor.BehaviorSubscription<T>[] EMPTY
Annotations
@SuppressWarnings:rawtypes
EMPTY_ARRAYback to summary
pack-priv static final Object[] EMPTY_ARRAY
indexback to summary
pack-priv long index
lockback to summary
pack-priv final ReadWriteLock lock
readLockback to summary
pack-priv final Lock readLock
subscribersback to summary
pack-priv final AtomicReference<BehaviorProcessor.BehaviorSubscription<T>[]> subscribers
terminalEventback to summary
pack-priv final AtomicReference<Throwable> terminalEvent
TERMINATEDback to summary
pack-priv static final BehaviorProcessor.BehaviorSubscription<T>[] TERMINATED
Annotations
@SuppressWarnings:rawtypes
valueback to summary
pack-priv final AtomicReference<Object> value
writeLockback to summary
pack-priv final Lock writeLock

Constructor Detail

BehaviorProcessorback to summary
pack-priv BehaviorProcessor()

Constructs an empty BehaviorProcessor.

Annotations
@SuppressWarnings:unchecked
Since
2.0
BehaviorProcessorback to summary
pack-priv BehaviorProcessor(T defaultValue)

Constructs a BehaviorProcessor with the given initial value.

Parameters
defaultValue:T

the initial value, not null (verified)

Exceptions
NullPointerException:
if defaultValue is null
Since
2.0

Method Detail

addback to summary
pack-priv boolean add(BehaviorProcessor.BehaviorSubscription<T> rs)
createback to summary
public static <T> @NonNull BehaviorProcessor<T> create()

Creates a BehaviorProcessor without a default item.

Parameters
<T>
the type of item the BehaviorProcessor will emit
Returns:@NonNull BehaviorProcessor<T>

the constructed BehaviorProcessor

Annotations
@CheckReturnValue
@NonNull
createDefaultback to summary
public static <T> @NonNull BehaviorProcessor<T> createDefault(T defaultValue)

Creates a BehaviorProcessor that emits the last item it observed and all subsequent items to each Subscriber that subscribes to it.

Parameters
<T>
the type of item the BehaviorProcessor will emit
defaultValue:T

the item that will be emitted first to any Subscriber as long as the BehaviorProcessor has not yet observed any items from its source Observable

Returns:@NonNull BehaviorProcessor<T>

the constructed BehaviorProcessor

Annotations
@CheckReturnValue
@NonNull
Exceptions
NullPointerException:
if defaultValue is null
getThrowableback to summary
public @Nullable Throwable getThrowable()

Implements abstract io.reactivex.rxjava3.processors.FlowableProcessor.getThrowable.

Doc from io.reactivex.rxjava3.processors.FlowableProcessor.getThrowable.

Returns the error that caused the FlowableProcessor to terminate or null if the FlowableProcessor hasn't terminated yet.

The method is thread-safe.

Returns:@Nullable Throwable

the error that caused the FlowableProcessor to terminate or null if the FlowableProcessor hasn't terminated yet

Annotations
@Override
@Nullable
@CheckReturnValue
getValueback to summary
public T getValue()

Returns a single value the BehaviorProcessor currently has or null if no such value exists.

The method is thread-safe.

Returns:T

a single value the BehaviorProcessor currently has or null if no such value exists

Annotations
@Nullable
@CheckReturnValue
hasCompleteback to summary
public boolean hasComplete()

Implements abstract io.reactivex.rxjava3.processors.FlowableProcessor.hasComplete.

Doc from io.reactivex.rxjava3.processors.FlowableProcessor.hasComplete.

Returns true if the FlowableProcessor has reached a terminal state through a complete event.

The method is thread-safe.

Returns:boolean

true if the FlowableProcessor has reached a terminal state through a complete event

Annotations
@Override
@CheckReturnValue
hasSubscribersback to summary
public boolean hasSubscribers()

Implements abstract io.reactivex.rxjava3.processors.FlowableProcessor.hasSubscribers.

Doc from io.reactivex.rxjava3.processors.FlowableProcessor.hasSubscribers.

Returns true if the FlowableProcessor has subscribers.

The method is thread-safe.

Returns:boolean

true if the FlowableProcessor has subscribers

Annotations
@Override
@CheckReturnValue
hasThrowableback to summary
public boolean hasThrowable()

Implements abstract io.reactivex.rxjava3.processors.FlowableProcessor.hasThrowable.

Doc from io.reactivex.rxjava3.processors.FlowableProcessor.hasThrowable.

Returns true if the FlowableProcessor has reached a terminal state through an error event.

The method is thread-safe.

Returns:boolean

true if the FlowableProcessor has reached a terminal state through an error event

Annotations
@Override
@CheckReturnValue
hasValueback to summary
public boolean hasValue()

Returns true if the BehaviorProcessor has any value.

The method is thread-safe.

Returns:boolean

true if the BehaviorProcessor has any value

Annotations
@CheckReturnValue
offerback to summary
public boolean offer(T t)

Tries to emit the item to all currently subscribed Subscribers if all of them has requested some value, returns false otherwise.

This method should be called in a sequential manner just like the onXXX methods of this BehaviorProcessor.

History: 2.0.8 - experimental

Parameters
t:T

the item to emit, not null

Returns:boolean

true if the item was emitted to all Subscribers

Annotations
@CheckReturnValue
Exceptions
NullPointerException:
if t is null
Since
2.2
onCompleteback to summary
public void onComplete()

Implements org.reactivestreams.Subscriber.onComplete.

Doc from org.reactivestreams.Subscriber.onComplete.

Successful terminal state.

No further events will be sent even if Subscription#request(long) is invoked again.

Annotations
@Override
onErrorback to summary
public void onError(@NonNull Throwable t)

Implements org.reactivestreams.Subscriber.onError.

Doc from org.reactivestreams.Subscriber.onError.

Failed terminal state.

No further events will be sent even if Subscription#request(long) is invoked again.

Parameters
t:@NonNull Throwable

the throwable signaled

Annotations
@Override
onNextback to summary
public void onNext(T t)

Implements org.reactivestreams.Subscriber.onNext.

Doc from org.reactivestreams.Subscriber.onNext.

Data notification sent by the Publisher in response to requests to Subscription#request(long).

Parameters
t:T

the element signaled

Annotations
@Override
onSubscribeback to summary
public void onSubscribe(@NonNull Subscription s)

Implements org.reactivestreams.Subscriber.onSubscribe.

Doc from org.reactivestreams.Subscriber.onSubscribe.

Invoked after calling Publisher#subscribe(Subscriber).

No data will start flowing until Subscription#request(long) is invoked.

It is the responsibility of this Subscriber instance to call Subscription#request(long) whenever more data is wanted.

The Publisher will send notifications only in response to Subscription#request(long).

Parameters
s:@NonNull Subscription

the Subscription that allows requesting data via Subscription#request(long)

Annotations
@Override
removeback to summary
pack-priv void remove(BehaviorProcessor.BehaviorSubscription<T> rs)
Annotations
@SuppressWarnings:unchecked
setCurrentback to summary
pack-priv void setCurrent(Object o)
subscribeActualback to summary
protected void subscribeActual(@NonNull Subscriber<? super T> s)
Annotations
@Override
subscriberCountback to summary
pack-priv int subscriberCount()
Annotations
@CheckReturnValue
terminateback to summary
pack-priv BehaviorProcessor.BehaviorSubscription<T>[] terminate(Object terminalValue)
Annotations
@SuppressWarnings:unchecked
io.reactivex.rxjava3.processors back to summary

pack-priv final Class BehaviorProcessor.BehaviorSubscription<T>

extends AtomicLong
implements Subscription, AppendOnlyLinkedArrayList.NonThrowingPredicate<Object>
Class Inheritance
All Implemented Interfaces
io.reactivex.rxjava3.internal.util.AppendOnlyLinkedArrayList.NonThrowingPredicate, io.reactivex.rxjava3.functions.Predicate, org.reactivestreams.Subscription

Field Summary

Modifier and TypeField and Description
pack-priv volatile boolean
pack-priv final Subscriber<? super T>
pack-priv boolean
pack-priv boolean
pack-priv long
pack-priv boolean
pack-priv AppendOnlyLinkedArrayList<Object>
private static final long
pack-priv final BehaviorProcessor<T>

Constructor Summary

AccessConstructor and Description
pack-priv
BehaviorSubscription(Subscriber<? super T> actual, BehaviorProcessor<T> state)

Method Summary

Modifier and TypeMethod and Description
public void
cancel()

Implements org.reactivestreams.Subscription.cancel.

Request the Publisher to stop sending data and clean up resources.
pack-priv void
pack-priv void
pack-priv void
emitNext(Object value, long stateIndex)

public boolean
public void
request(long
the strictly positive number of elements to requests to the upstream Publisher
n
)

Implements org.reactivestreams.Subscription.request.

No events will be sent by a Publisher until demand is signaled via this method.
public boolean
test(Object
the value
o
)

Implements io.reactivex.rxjava3.internal.util.AppendOnlyLinkedArrayList.NonThrowingPredicate.test.

Test the given input value and return a boolean.
Inherited from java.util.concurrent.atomic.AtomicLong:
accumulateAndGetaddAndGetcompareAndExchangecompareAndExchangeAcquirecompareAndExchangeReleasecompareAndSetdecrementAndGetdoubleValuefloatValuegetgetAcquiregetAndAccumulategetAndAddgetAndDecrementgetAndIncrementgetAndSetgetAndUpdategetOpaquegetPlainincrementAndGetintValuelazySetlongValuesetsetOpaquesetPlainsetReleasetoStringupdateAndGetweakCompareAndSetweakCompareAndSetAcquireweakCompareAndSetPlainweakCompareAndSetReleaseweakCompareAndSetVolatile

Field Detail

cancelledback to summary
pack-priv volatile boolean cancelled
downstreamback to summary
pack-priv final Subscriber<? super T> downstream
emittingback to summary
pack-priv boolean emitting
fastPathback to summary
pack-priv boolean fastPath
indexback to summary
pack-priv long index
nextback to summary
pack-priv boolean next
queueback to summary
pack-priv AppendOnlyLinkedArrayList<Object> queue
serialVersionUIDback to summary
private static final long serialVersionUID

Hides java.util.concurrent.atomic.AtomicLong.serialVersionUID.

stateback to summary
pack-priv final BehaviorProcessor<T> state

Constructor Detail

BehaviorSubscriptionback to summary
pack-priv BehaviorSubscription(Subscriber<? super T> actual, BehaviorProcessor<T> state)

Method Detail

cancelback to summary
public void cancel()

Implements org.reactivestreams.Subscription.cancel.

Doc from org.reactivestreams.Subscription.cancel.

Request the Publisher to stop sending data and clean up resources.

Data may still be sent to meet previously signalled demand after calling cancel.

Annotations
@Override
emitFirstback to summary
pack-priv void emitFirst()
emitLoopback to summary
pack-priv void emitLoop()
emitNextback to summary
pack-priv void emitNext(Object value, long stateIndex)
isFullback to summary
public boolean isFull()
requestback to summary
public void request(long n)

Implements org.reactivestreams.Subscription.request.

Doc from org.reactivestreams.Subscription.request.

No events will be sent by a Publisher until demand is signaled via this method.

It can be called however often and whenever needed—but if the outstanding cumulative demand ever becomes Long.MAX_VALUE or more, it may be treated by the Publisher as "effectively unbounded".

Whatever has been requested can be sent by the Publisher so only signal demand for what can be safely handled.

A Publisher can send less than is requested if the stream ends but then must emit either Subscriber#onError(Throwable) or Subscriber#onComplete().

Parameters
n:long

the strictly positive number of elements to requests to the upstream Publisher

Annotations
@Override
testback to summary
public boolean test(Object o)

Implements io.reactivex.rxjava3.internal.util.AppendOnlyLinkedArrayList.NonThrowingPredicate.test.

Doc from io.reactivex.rxjava3.functions.Predicate.test.

Test the given input value and return a boolean.

Parameters
o:Object

the value

Returns:boolean

the boolean result

Annotations
@Override