Skip to content

Subject

David Gross edited this page May 19, 2014 · 22 revisions

A Subject is a sort of bridge or proxy that acts both as an Subscriber and as an Observable. Because it is a Subscriber, it can subscribe to one or more Observables, and because it is an Observable, it can pass through the items it observes by reemitting them, and it can also emit new items.

If you have a Subject and you want to pass it along to some other agent without exposing its Subscriber interface, you can mask it by calling its asObservable method, which will return the Subject as a pure Observable.

see also:

There are four subclasses of Subject that are designed for particular use cases:

AsyncSubject

AsyncSubject emits the last value (and only the last value) emitted by the source Observable, and only after that source Observable completes. (If the source Observable does not emit any values, the AsyncSubject also completes without emitting any values.) It will also emit this same final value to any subsequent Subscribers. However, if the source Observable terminates with an error, the AsyncSubject will not emit any items, but will simply pass along the error notification from the source Observable.

see also:

BehaviorSubject

When an Subscriber subscribes to a BehaviorSubject, it begins by emitting the item most recently emitted by the source Observable (or a seed/default value if none has yet been emitted) and then continues to emit any other items emitted later by the source Observable(s). However, if the source Observable terminates with an error, the BehaviorSubject will not emit any items to subsequent Subscribers, but will simply pass along the error notification from the source Observable.

see also:

PublishSubject

PublishSubject emits to a subscriber only those items that are emitted by the source Observable(s) subsequent to the time of the subscription. If the source Observable terminates with an error, the PublishSubject will not emit any items to subsequent Subscribers, but will simply pass along the error notification from the source Observable. Note: In RxJava's Scala language adaptor, you instantiate a PublishSubject via Subject.

see also:

ReplaySubject

ReplaySubject emits to any subscriber all of the items that were emitted by the source Observable(s), regardless of when the subscriber subscribes.

There are also versions of ReplaySubject that will throw away old items once the replay buffer threatens to grow beyond a certain size, or when a specified timespan has passed since the items were originally emitted.

When using ReplaySubject as a Subscriber, take care not to call its onNext( ) method (or its other on methods) from multiple threads, as this could lead to coincident (non-sequential) calls, which violates the Observable contract and creates an ambiguity in the resulting Subject as to which item or emission should be replayed first.

see also:

Clone this wiki locally