Angular Observables and Subject with an example

Posted By : Milind Ahuja | 18-Sep-2018

This blog will show you the use of Observables and Subject in Angular Applications to watch changes in local storage. For that let's understand briefly what these terms mean and why we use them.

Observable and Subject belongs to RxJS library. To perform asynchronous programming in Angular, either Observable or Promise can be used. To send and receive data over HTTP, we deal it asynchronously as this process may take some time. We have to subscribe Observables by using the subscribe method to get the data. 

Observable is a class of RxJS library, a Reactive extension for JavaScript that helps us perform reactive programming. To understand Observable let's say we have a service which requests the database using the HTTP get a call to fetch the data, and in return, we get an Observable of type response. So we can say, an Observable is nothing but a sequence of items that arrive asynchronously over time. One thing to keep in mind, with HTTP calls it is always a single item and that single item is nothing but the HTTP response. So the Observable we receive in the above case is just a single item which is nothing but the HTTP response object. So we have made a request and got the response but the response is an Observable which is not the desired format, so we are going to map this Observable into JSON format. No, we have the JSON data which we provide to the components which subscribe to this observable.

On the other hand, a RxJS subject is also a special Observable type that allows values to be multicasted to many Observers. While the simple Observables are uncast, i.e. each subscribed Observer has an independent execution of the Observable, Subjects are multicast. Subjects are like EventEmitters and maintain a registry of many listeners. Every Subject is an Observable and an Observer.It means that data can be emitted by a Subject, on top of having the capability to be subscribed to. It contains methods like next(), error() and complete(). To feed the Subject with a new value, just call next(value), and it will be multicasted to the observers registered to listen to the Subject.

To use RxJS library in your Angular application, we need to have RxJS. If we are using Angular CLI, it installs RxJS by default. If not, we can simply install with: npm install rxjs --save command.

Now that we know the basics about Observables and Subject, let us use these in a simple example in which we watch for the changes in local storage. For that let us make a service that watches for the changes in local storage.

In the example below, we are setting a language in local storage and also watching if it changes for example if a user selects another language.

import { Injectable } from '@angular/core';
//To use Observable and Subject in our Angular application, we need to import it as following.
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class StorageService {
  //Create a Subject
  private storageSub= new Subject();

  watchStorage(): Observable {
    return this.storageSub.asObservable();
  }
//Why we use asObservable? 
//The subject is private and not exposed outside the message service so it can't be subscribed to directly. You shouldn't expose the subject 
//because it can be used to broadcast messages to subscribers which is the responsibility of the message service, instead you should expose an 
//observable to subscribers because it can only be used for receiving messages.

  setItem(key: string, data: any) {
    localStorage.setItem(key, data);
    this.storageSub.next(data);
  }
//An EventEmitter, extends Subject. You fire off an event that all subscribers will listen too, whenever you use next

  getItem() {
    return localStorage.getItem('currentLang');
    }
}

Now let's see our component where we call this watch function from their service :

import {Component, OnInit} from "@angular/core";
import { StorageService } from "../app.service";

@Component({
  selector: 'my-page',
  templateUrl: './my-page.component.html'
})

export class MyComponent implements OnInit{

  public currentLang;
  constructor(private storageService: StorageService){}

  ngOnInit(){
    this.getCurrentLang();

    this.storageService.watchStorage().subscribe((data:string) => {
        this.currentLang = data;
        console.log('watched for change', this.currentLang);
      })
  }
}

So this was all about Observable and Subject with a simple example.

THANKS

About Author

Author Image
Milind Ahuja

Milind is a bright Lead Frontend Developer and have knowledge of HTML, CSS, JavaScript, AngularJS, Angular 2+ Versions and photoshop. His hobbies are learning new computer techniques, fitness and interest in different languages.

Request for Proposal

Name is required

Comment is required

Sending message..