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

public final Class BehaviorSubject<T>

extends Subject<T>
Class Inheritance
Type Parameters
<T>
the type of item expected to be observed by the Subject
Imports
java.util.Objects, java.util.concurrent.atomic.AtomicReference, java.util.concurrent.locks.*, io.reactivex.rxjava3.annotations.*, io.reactivex.rxjava3.core.Observer, io.reactivex.rxjava3.disposables.Disposable, io.reactivex.rxjava3.internal.util.*, .AppendOnlyLinkedArrayList.NonThrowingPredicate, io.reactivex.rxjava3.plugins.RxJavaPlugins

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

This subject does not have a public constructor by design; a new empty instance of this BehaviorSubject 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 Observable.create that creates an Observable, not a BehaviorSubject).

Since a Subject is conceptionally derived from the Processor type in the Reactive Streams specification, nulls are not allowed (Rule 2.13) as default initial values in createDefault(Object) or as parameters to onNext(Object) and onError(Throwable). Such calls will result in a NullPointerException being thrown and the subject's state is not changed.

Since a BehaviorSubject is an io.reactivex.rxjava3.core.Observable, it does not support backpressure.

When this BehaviorSubject is terminated via onError(Throwable) or onComplete(), the last observed item (if any) is cleared and late io.reactivex.rxjava3.core.Observers only receive the respective terminal event.

The BehaviorSubject 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 Observers subscribe through a filter whose predicate filters out this special item:


BehaviorSubject<Integer> subject = BehaviorSubject.create();

final Integer EMPTY = Integer.MIN_VALUE;

Observable<Integer> observable = subject.filter(v -> v != EMPTY);

TestObserver<Integer> to1 = observable.test();

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

TestObserver<Integer> to2 = observable.test();

subject.onNext(2);
subject.onComplete();

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

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

// Observers coming after the subject was terminated receive
// no items and only the onComplete event in this case.
observable.test().assertResult();

Even though BehaviorSubject implements the Observer interface, calling onSubscribe is not required (Rule 2.12) if the subject is used as a standalone source. However, calling onSubscribe after the BehaviorSubject reached its terminal state will result in the given Disposable being disposed 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 toSerialized() method available to all Subjects provides such serialization and also protects against reentrance (i.e., when a downstream Observer consuming this subject also wants to call onNext(Object) on this subject recursively).

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

Scheduler:
BehaviorSubject does not operate by default on a particular io.reactivex.rxjava3.core.Scheduler and the Observers get notified on the thread the respective onXXX methods were invoked.
Error handling:
When the onError(Throwable) is called, the BehaviorSubject enters into a terminal state and emits the same Throwable instance to the last set of Observers. During this emission, if one or more Observers dispose their respective Disposables, the Throwable is delivered to the global error handler via io.reactivex.rxjava3.plugins.RxJavaPlugins#onError(Throwable) (multiple times if multiple Observers cancel at once). If there were no Observers subscribed to this BehaviorSubject when the onError() was called, the global error handler is not invoked.

Example usage:

 // observer will receive all 4 events (including "default").
 BehaviorSubject<Object> subject = BehaviorSubject.createDefault("default");
 subject.subscribe(observer);
 subject.onNext("one");
 subject.onNext("two");
 subject.onNext("three");

 // observer will receive the "one", "two" and "three" events, but not "zero"
 BehaviorSubject<Object> subject = BehaviorSubject.create();
 subject.onNext("zero");
 subject.onNext("one");
 subject.subscribe(observer);
 subject.onNext("two");
 subject.onNext("three");

 // observer will receive only onComplete
 BehaviorSubject<Object> subject = BehaviorSubject.create();
 subject.onNext("zero");
 subject.onNext("one");
 subject.onComplete();
 subject.subscribe(observer);

 // observer will receive only onError
 BehaviorSubject<Object> subject = BehaviorSubject.create();
 subject.onNext("zero");
 subject.onNext("one");
 subject.onError(new RuntimeException("error"));
 subject.subscribe(observer);
  

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 BehaviorSubject.BehaviorDisposable<T>[]
pack-priv long
pack-priv final ReadWriteLock
pack-priv final AtomicReference<BehaviorSubject.BehaviorDisposable<T>[]>
pack-priv final Lock
pack-priv final AtomicReference<Throwable>
pack-priv static final BehaviorSubject.BehaviorDisposable<T>[]
pack-priv final AtomicReference<Object>
pack-priv final Lock

Constructor Summary

AccessConstructor and Description
pack-priv
BehaviorSubject(T
the initial value, not null (verified)
defaultValue
)

Constructs an empty BehaviorSubject.

Method Summary

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

Returns:

the constructed BehaviorSubject
create
()

Creates a BehaviorSubject without a default item.

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

Returns:

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

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

public @Nullable Throwable
getThrowable()

Implements abstract io.reactivex.rxjava3.subjects.Subject.getThrowable.

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

Returns:

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

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

public boolean
hasComplete()

Implements abstract io.reactivex.rxjava3.subjects.Subject.hasComplete.

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

Implements abstract io.reactivex.rxjava3.subjects.Subject.hasObservers.

Returns true if the subject has any Observers.
public boolean
hasThrowable()

Implements abstract io.reactivex.rxjava3.subjects.Subject.hasThrowable.

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

Returns:

true if the subject has any value
hasValue
()

Returns true if the subject has any value.

public void
onComplete()

Implements io.reactivex.rxjava3.core.Observer.onComplete.

Notifies the Observer that the Observable has finished sending push-based notifications.
public void
public void
onNext(T
the item emitted by the Observable
t
)

Implements io.reactivex.rxjava3.core.Observer.onNext.

Provides the Observer with a new item to observe.
public void
pack-priv void
pack-priv void
protected void
subscribeActual(Observer<? super T> observer)

pack-priv int
pack-priv BehaviorSubject.BehaviorDisposable<T>[]
terminate(Object terminalValue)

Inherited from io.reactivex.rxjava3.subjects.Subject:
toSerialized

Field Detail

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

Constructor Detail

BehaviorSubjectback to summary
pack-priv BehaviorSubject(T defaultValue)

Constructs an empty BehaviorSubject.

Parameters
defaultValue:T

the initial value, not null (verified)

Annotations
@SuppressWarnings:unchecked
Since
2.0

Method Detail

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

Creates a BehaviorSubject without a default item.

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

the constructed BehaviorSubject

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

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

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

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

Returns:@NonNull BehaviorSubject<T>

the constructed BehaviorSubject

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

Implements abstract io.reactivex.rxjava3.subjects.Subject.getThrowable.

Doc from io.reactivex.rxjava3.subjects.Subject.getThrowable.

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

The method is thread-safe.

Returns:@Nullable Throwable

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

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

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

The method is thread-safe.

Returns:T

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

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

Implements abstract io.reactivex.rxjava3.subjects.Subject.hasComplete.

Doc from io.reactivex.rxjava3.subjects.Subject.hasComplete.

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

The method is thread-safe.

Returns:boolean

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

Annotations
@Override
@CheckReturnValue
hasObserversback to summary
public boolean hasObservers()

Implements abstract io.reactivex.rxjava3.subjects.Subject.hasObservers.

Doc from io.reactivex.rxjava3.subjects.Subject.hasObservers.

Returns true if the subject has any Observers.

The method is thread-safe.

Returns:boolean

true if the subject has any Observers

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

Implements abstract io.reactivex.rxjava3.subjects.Subject.hasThrowable.

Doc from io.reactivex.rxjava3.subjects.Subject.hasThrowable.

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

The method is thread-safe.

Returns:boolean

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

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

Returns true if the subject has any value.

The method is thread-safe.

Returns:boolean

true if the subject has any value

Annotations
@CheckReturnValue
onCompleteback to summary
public void onComplete()

Implements io.reactivex.rxjava3.core.Observer.onComplete.

Doc from io.reactivex.rxjava3.core.Observer.onComplete.

Notifies the Observer that the Observable has finished sending push-based notifications.

The Observable will not call this method if it calls onError.

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

Implements io.reactivex.rxjava3.core.Observer.onNext.

Doc from io.reactivex.rxjava3.core.Observer.onNext.

Provides the Observer with a new item to observe.

The Observable may call this method 0 or more times.

The Observable will not call this method again after it calls either onComplete or onError.

Parameters
t:T

the item emitted by the Observable

Annotations
@Override
onSubscribeback to summary
public void onSubscribe(Disposable d)
Annotations
@Override
removeback to summary
pack-priv void remove(BehaviorSubject.BehaviorDisposable<T> rs)
Annotations
@SuppressWarnings:unchecked
setCurrentback to summary
pack-priv void setCurrent(Object o)
subscribeActualback to summary
protected void subscribeActual(Observer<? super T> observer)
Annotations
@Override
subscriberCountback to summary
pack-priv int subscriberCount()
Annotations
@CheckReturnValue
terminateback to summary
pack-priv BehaviorSubject.BehaviorDisposable<T>[] terminate(Object terminalValue)
Annotations
@SuppressWarnings:unchecked
io.reactivex.rxjava3.subjects back to summary

pack-priv final Class BehaviorSubject.BehaviorDisposable<T>

extends Object
implements Disposable, AppendOnlyLinkedArrayList.NonThrowingPredicate<Object>
Class Inheritance
  • java.lang.Object
  • io.reactivex.rxjava3.subjects.BehaviorSubject.BehaviorDisposable
All Implemented Interfaces
io.reactivex.rxjava3.internal.util.AppendOnlyLinkedArrayList.NonThrowingPredicate, io.reactivex.rxjava3.functions.Predicate, io.reactivex.rxjava3.disposables.Disposable

Field Summary

Modifier and TypeField and Description
pack-priv volatile boolean
pack-priv final Observer<? super T>
pack-priv boolean
pack-priv boolean
pack-priv long
pack-priv boolean
pack-priv AppendOnlyLinkedArrayList<Object>
pack-priv final BehaviorSubject<T>

Constructor Summary

AccessConstructor and Description
pack-priv
BehaviorDisposable(Observer<? super T> actual, BehaviorSubject<T> state)

Method Summary

Modifier and TypeMethod and Description
public void
dispose()

Implements io.reactivex.rxjava3.disposables.Disposable.dispose.

Dispose the resource, the operation should be idempotent.
pack-priv void
pack-priv void
pack-priv void
emitNext(Object value, long stateIndex)

public boolean
isDisposed()

Implements io.reactivex.rxjava3.disposables.Disposable.isDisposed.

Returns true if this resource has been disposed.
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.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

cancelledback to summary
pack-priv volatile boolean cancelled
downstreamback to summary
pack-priv final Observer<? 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
stateback to summary
pack-priv final BehaviorSubject<T> state

Constructor Detail

BehaviorDisposableback to summary
pack-priv BehaviorDisposable(Observer<? super T> actual, BehaviorSubject<T> state)

Method Detail

disposeback to summary
public void dispose()

Implements io.reactivex.rxjava3.disposables.Disposable.dispose.

Doc from io.reactivex.rxjava3.disposables.Disposable.dispose.

Dispose the resource, the operation should be idempotent.

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)
isDisposedback to summary
public boolean isDisposed()

Implements io.reactivex.rxjava3.disposables.Disposable.isDisposed.

Doc from io.reactivex.rxjava3.disposables.Disposable.isDisposed.

Returns true if this resource has been disposed.

Returns:boolean

true if this resource has been disposed

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