Back to overview

RxJS Subject

RxJS

Different Types of Subject

Subject

A Subject is a special type of Observable that implements the Observer interface.

It's a special type of Observable that is also an Observer.

Subject is multicast.

actionSubject = new Subject<string>();

// Call next() to emit items
this.actionSubject.next('tools');

// Call subscribe() to receive notifications
this.actionSubject.subscribe((item) => console.log(item));
Limitations

when a new subscriber is created using the subscribe method, it won’t receive an event until the next time the next method is called. this can be unhelpful if you are creating instances of components or directives dynamically and you want them to have some context data as soon as they are created.

BehaviorSubject

A special type of Subject that

  • Buffers its last emitted value
  • Emits that value to any late subscribers
  • Requires a default value
  • Emits that default value if it hasn't yet emitted any items
aSub = new BehaviorSubject<number>(0);

Use BehaviorSubject if you want an initial value.

Very Important when using combineLatest.

BehaviorSubject class keeps track of the last event it processed and sends it to new subscribers as soon as they call the subscribe method.

ReplaySubject

ReplaySubject class does something similar, except that it keeps track of all of its events and sends them all to new subscribers, allowing them to catch up with any events that were sent before they subscribed.