Add and update values in BehaviorSubject (Angular)

BehaviorSubject example

The BehaviorSubject is one of the 4 variants of RxJS Subjects (“a special type of Observable which shares a single execution path among observers”).
The BehaviorSubject keeps the last emitted value from the observable object and can be returned to the subscribers.

One useful usage of it is to be populated with the response data returned from an HTTP request.
This can be done like this (Angular code snippet):

import { HttpClient } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
import { tap } from 'rxjs/operators';
import { IMySubject } from '@interfaces';

export class SubjectExampleService {
  private _subject: BehaviorSubject<IMySubject> = new BehaviorSubject(null);

  public subject$: Observable<IMySubject> = this._subject.asObservable();

  constructor(private _http: HttpClient) {

  getTestData() {
    return this._http
        tap((response: IMySubject) =>

The above code snipped represents the creation of an Observable service.
We are encapsulating our logic, hide the BehaviorSubject, and return a public observable object to which the consumers can subscribe and always have the latest emitted response value from the service.
Note that adding a value to the BehaviorSubject is done by

Update BeahviorSubject

Occasionally you can fall into a scenario where you would need to update the Subject manually. For instance, if there is another operation happening which updates some property of our IMySubject object from the given example above.

In that case we can add another method in the SubjectExampleService service and update the BehaviorSubject from within with the following syntax:

updateSubjectData(theChangedProp: string) {{ 
    ...this._subject.value, mySpecialProperty: theChangedProp 

We call and pass as a first argument the value of the current object. The second parameter is the name of the property to be changed and the new value.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s