What is the difference between BehaviorSubject and Observable?

BehaviorSubject is a variant of Subject, a type of Observable to which one can “subscribe” like any other Observable.

Features of BehaviorSubject

  • It needs an initial value as it must always return a value upon subscription, even if it has not received the method next()
  • Upon subscription, it returns the last value of the Subject. A regular Observable is only triggered when it receives the method onNext()
  • At any point, one can retrieve the last value of the Subject in a non-Observable using the method getValue()

Features of Subject

  • Subject is an “observer” in addition to being an Observable; therefore, one can also send values to a Subject while also subscribing to it
  • One can get a value from BehaviorSubject using the method asObservable()

Example 1 using BehaviorSubject

// BehaviorSubject.
// 'A' is an initial value. If there is a Subscription 
// after it, it would immediately get the value 'A'.

beSubject = new BehaviorSubject('a'); 

beSubject.next('b');

beSubject.subscribe(value => {
  console.log('Subscription received the value ', value);

  // Subscription received B. It would not happen
  // for an Observable or Subject by default.
});

beSubject.next('c');
// Subscription received C.

beSubject.next('d');
// Subscription received D.

Example 2 using Subject

// Subject.

subject = new Subject(); 

subject.next('b');

subject.subscribe(value => {
  console.log('Subscription received the value ', value);

  // Subscription won't receive anything at this point.
});

subject.next('c');
// Subscription received C.

subject.next('d');
// Subscription received D.

An Observable can be created from both Subject and BehaviorSubject; for example, subjectName.asObservable().

The only difference is that one cannot send values to an Observable using the method next().

In Angular, it is recommended to use BehaviorSubject for transferring data as a Service is often initialised before a component.

BehaviorSubject ensures that the component consuming the Service receives the last updated data, even if there are no new updates, due to the subscription of the component to the Service.

Leave a Comment