A Subject is a sort of bridge or proxy that is available in some implementations of ReactiveX that acts both as
an observer and as an Observable. Because it is an observer, 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.
Because a Subject subscribes to an Observable, it will trigger that Observable to begin emitting items (if that
Observable is “cold” — that is, if it waits for a subscription before it begins to emit items). This can have
the effect of making the resulting Subject a “hot” Observable variant of the original “cold” Observable.
In most ReactiveX implementations, especially those that can run in a multi-threaded environment, subjects on their observer side are not considered thread safe.
However, the observable side, i.e., Subscribe() is always thread safe.
This means that calling OnNext, OnError or OnCompleted from multiple threads can result in an undefined state.
Most ReactiveX implementations therefore offer a special operator that makes the observer side thread safe as well. Look for the ToSerialized operator.
Varieties of Subject
There are four varieties of Subject that are designed for particular use cases. Not all of these
are available in all implementations, and some implementations use other naming conventions (for example, in
RxScala, what is called a “PublishSubject” here is known simply as a “Subject”):
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.
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.
If you have a Subject and you want to pass it along to some other agent without exposing its
Observer interface, you can mask it by calling its hide method, which
will return the Subject as a pure Observable.