2/25/2018 - 6:05 AM

Subject vs BehaviorSubject

/* A BehaviorSubject holds one value. When it is subscribed it emits the value immediately. A Subject doesn't hold a value. */

const subject = new Rx.Subject();;
subject.subscribe(x => console.log(x));
// Console output will be empty

const subject = new Rx.BehaviorSubject();;
subject.subscribe(x => console.log(x));
// Console output: 1

// In addition:
// - BehaviorSubject can be created with initial value: new Rx.BehaviorSubject(1)
// - Consider ReplaySubject if you want the subject to hold more than one value

In Angular services, I would use BehaviorSubject for a data service as a angular service often initializes before component and behavior subject ensures that the component consuming the service receives the last updated data even if there are no new updates since the component's subscription to this data.