RxJava - Subjects

 

What is Subject?

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 re-emitting them, and it can also emit new items

 

The best way to use Subjects when we have an unknown number of sources and a single Observable. Subjects can be helpful for decoupling between Observable and Observers.

 

There are below type of subjects available

  • PublishSubject
  • BehaviorSubject
  • ReplaySubject
  • AsyncSubject
  • UnicastSubject

Publish Subject

Emits only those items which are emitted after time of subscription.

Behavior Subject

Upon subscription, emits the most recent item then continue to emit item emitted by the source Observable.

Replay Subject

Emits all the items emitted by source Observable regardless of when it has subscribed the Observable.

Async Subject

Emits the last item emitted by the source Observable after it's completes emission.

UnicastSubject

The last implementation is interesting and might be useful. It is similar to other Subjects. It is used to observe and subscribe to the sources