a blog for those who code

Wednesday, 20 March 2019

Understanding Observable - A key Concept in Angular

If you would have been working in Angular or you might have started learning Angular, you will definitely have heard about Observable, so what exactly it is and how we can use it in Angular. Observable in simple terms provide a support in your application to pass data a.k.a. messages between publishers and subscribers.

Lets say you have a function which publish values or say generate values which can be seen as publishers and you have a consumer/subscriber which consumes that values, now the publisher will not start generating values until the consumer subscribes for it and it will receive data until the function gets completed or if the consumer unsubscribe it.

To work with Observables we need to use RxJS library which gives us an implementation of Observables for JavaScript. A simple example of RxJS Observable implementation is :

import { interval } from 'rxjs'

const intervalObservable = interval(10);

intervalObservable.subscribe(num =>
  console.log('The number is ' + num)

In the above code we are creating an Observable that will publish a value on an interval and then we are subscribing to that Observable to get the data.

Let's create a Observable from Scratch without using an inbuilt one. The observables will emit the data on .next method, will throw an error through .error and it will not make any further calls, and will get completed on .complete if there is no error and it will stop any subsequent data emition.

Understanding Routing

import { Observable,Observer} from 'rxjs';

const myCustomObservable = Observable.create((observer: Observer<string>) => {
  setTimeout(() => {
    observer.next('After 5 seconds')
  }, 5000);

  setTimeout(() => {
    observer.next('After 10 seconds')
  }, 10000);

  setTimeout(() => {
     observer.error('Error after 15 seconds')
  }, 15000)

  setTimeout(() => {
  }, 20000)

So we have created our custom observable which will emit data after 5 and 10 seconds and throw an error after 15 seconds. Now lets use our custom observable and subscribe to it. In the below code my observable will emit data after 5 seconds and 10 seconds and then throw an error after 15 seconds. Do note that our subscription will not get completed because there is an error in our subscription.

const myCustomSubscrition = myCustomObservable.subscribe(
  (response: string) => { console.log(data); },
  (error: string) => { console.log(error); },
  () => { console.log('Completed');}

To test completion of Observables just comment out the code where observable was emitting error, then you can see our observable gets completed after 20 seconds. Now a good practice is to unsubscribe from your observables whenever you are leaving the component i.e. ngOnDestroy to avoid a potential memory leak. All the inbuilt Angular Observable takes care of unsubscription by itself but if you are creating custom observables you have to unsubscribe it.


(Also Read : Custom Bindings Using Input and Output)

As of now we have learned about Observables, now the main question is how we can use it in Angular. When you are developing an Angular Application, might be you will not create your Observables very often but you will surely subscribe to the Inbuilt Angular Observables, so let's go through some of them :

1. EventEmitter - EventEmitter uses Observables to emit custom events when publishing values from a component through the @Output() decorator. An Output property is an observable property which always returns an Angular EventEmitter where the values flows out of the component. That means, in a simple way letting the parent component know that something has changed in the child component.
2. HTTP - HttpClient of Angular returns observables.
3. Router.events - Router Events provides events as observables

I think now you have basic understanding of Observables and how to use it in your Angular Application.

No comments:

Post a Comment