Observables With Angular 5

We have a case where we use observable to populate the UI from the external data asynchronously. Angular uses same thing for this task. Let’s see how we can use the observables and use them in an Angular application.

What are Observables?

Observables are lazy collections of multiple values or we can say, data over a period. Observables open the continuous channel of communication where multiple values are emitted over time. This allows us to determine the pattern of the data.

In a real-world example, we can say Internet service offered by the mobile is observable. It is available only to the people who have subscribed to it. We continuously receive this service from the service provider only until this service is ON and subscribed.

Creating the basic observable

Let’s create the basic observable first and let’s see what they offer us. The code snippet for the same can be like below.

  1. import { Component, OnInit } from '@angular/core';  
  2. import {Observable} from 'rxjs/Observable'  
  3. @Component({  
  4.   selector: 'app-observable-demo',  
  5.   templateUrl: './observable-demo.component.html',  
  6.   styleUrls: ['./observable-demo.component.css']  
  7. })  
  8. export class ObservableDemoComponent implements OnInit  
  9.  {  
  10.   private data: Observable<string>;  
  11.   private fruits: Array<string> = [];  
  12.   private anyErrors: boolean;  
  13.   private finished: boolean;  
  14.   
  15.   processed=false;  
  16.   
  17.   constructor() { }  
  18. ngOnInit(){  
  19. }  
  20.   
  21. Start(){  
  22.   this.data = new Observable  
  23.   (  
  24.     observer =>   
  25.     {  
  26.             setTimeout(() =>   
  27.             {  
  28.                 observer.next('Apple');  
  29.             }, 1000);  
  30.               
  31.             setTimeout(() =>   
  32.             {  
  33.                 observer.next('mango');  
  34.             }, 2000);  
  35.             setTimeout(() =>   
  36.             {  
  37.                 observer.next('Orannge');  
  38.             }, 3000);  
  39.             setTimeout(() =>   
  40.             {  
  41.                 observer.complete();  
  42.             }, 4000);  
  43.               
  44.    }  
  45. );  
  46. let subscription = this.data. subscribe(  
  47. fruit => this.fruits.push(fruit),  
  48.     error => this.anyErrors = false,  
  49.     () => this.finished = true  
  50. );  
  51. this.processed=true; }}  

Let’s see the code description step by step,

  1. Import the observable from rxjs/Observable and include in the component
  2. next is to create the observable object which in our example we are creating the observable object which will be of string
  3. Next thing is to subscribe the Observable in the application which will allow us to listen to the data that is coming along with it
  4. While subscription we used three callbacks first which already accepts the data emitted by

The second observable is the Error call back, and the third one is the successful callback which will be called when the whole data has been received.

To invoke this observable, we need to do some changes at the template that we are doing. The code snippet for the template can be like this,

  1. <p style="padding-left:300px;font-weight:bold;font-size: 50px">Observable Basics</p>  
  2. <hr/>  
  3. <b>Observable Data </b>  
  4.  <div style="border: 3px;padding-left:150px;text-align: " *ngFor="let f of fruits"> {{ f | uppercase }}</div>  
  5.  <hr>  
  6. <div *ngIf='anyErrors' style="border: 3px;padding-left:0px" >  
  7.   <b>Error Status :</b>   
  8.  {{anyErrors==true'error occured ' : 'It All Good'}}   
  9.   <hr>  
  10. </div>  
  11. <div style="border: 3px;padding-left:0px"> <b> completion status : </b> {{ finished==true ? 'Observer completed ''' }}</div>  
  12. <hr>  
  13. <button style="margin-top: 2rem;" (click)="start()">Start Emitting</button>  

The above code displays the fruit names that we are emitting in the application output.
Angular

So, when we see the output, we will see the above output.

The next thing we want to see is how we can handle the error in observers.

Error Handling in Observables

There might be a case where an error is generated when we are using the observables. If some unexpected occurs in between, we can use the observable error function in our subscription to check what went wrong.

Let’s check the component code for the same.

  1. import { Component, OnInit } from '@angular/core';  
  2. import {Observable} from 'rxjs/Observable'  
  3. @Component({  
  4.   selector: 'app-observable-demo',  
  5.   templateUrl: './observable-demo.component.html',  
  6.   styleUrls: ['./observable-demo.component.css']  
  7. })  
  8. export class ObservableDemoComponent implements OnInit {  
  9.   private data: Observable<string>;  
  10.   private fruits: Array<string> = [];  
  11.   private anyErrors: boolean;  
  12.   private finished: boolean;  
  13.   
  14.   processed=false;  
  15.   
  16.   constructor() { }  
  17. ngOnInit(){  
  18. }  
  19.   
  20. start(){  
  21.   this.data = new Observable  
  22.   (  
  23.     observer =>   
  24.     {  
  25.             setTimeout(() =>   
  26.             {  
  27.                 observer.next('Apple');  
  28.             }, 1000);  
  29.               
  30.             setTimeout(() =>   
  31.             {  
  32.                 observer.next('mango');  
  33.             }, 2000);  
  34.             setTimeout(() =>   
  35.             {  
  36.                 observer.next('Orannge');  
  37.             }, 3000);  
  38.             setTimeout(() =>   
  39.             {  
  40.                 observer.error(new Error('error occured'));  
  41.             }, 4000);  
  42.             setTimeout(() =>   
  43.             {  
  44.                 observer.complete();  
  45.             }, 5000); });  
  46. let subscription = this.data.  
  47. subscribe(  
  48.     fruit => this.fruits.push(fruit),  
  49.     error => this.anyErrors = true,  
  50.     () => this.finished = true  
  51. );  
  52. this.processed=true; }}  

We can see the output here like below.
Angular

Thing to consider in this case is that we cannot see the completion status shown when the Emit event is done

This is because the complete event won’t be fired if it is added after the error in the coding so we should always have some function which will stop all the running component in the application. 

Using observables for the Form Events

Let’s see how we use the observables in the angular forms

Component that we will be using will be like below,

  1. import { Component, OnInit } from '@angular/core';  
  2. import {Observable} from 'rxjs/Observable'  
  3. import {FormControl, FormGroup, FormBuilder} from '@angular/forms';  
  4. import 'rxjs/add/operator/map';  
  5.   
  6. @Component({  
  7.   selector: 'app-observable-demo',  
  8.   templateUrl: './observable-demo.component.html',  
  9.   styleUrls: ['./observable-demo.component.css']  
  10. })  
  11. export class ObservableDemoComponent implements OnInit {  
  12.   private data: Observable<string>;  
  13.   private fruits: Array<string> = [];  
  14.   private anyErrors: boolean;  
  15.   private finished: boolean;  
  16.   mathform: FormGroup;  
  17.   inputnumber :FormControl  
  18.   squaredata:number;  
  19.   processed=false;  
  20.   
  21.   constructor(private fb: FormBuilder) {  
  22.     
  23. this.inputnumber=new FormControl();  
  24.   
  25.     this.mathform = fb.group({  
  26.         inputnumber:this.inputnumber  
  27.     })  
  28. this.inputnumber.valueChanges.map(n=>n*n)  
  29.     .subscribe(power=>this.squaredata=power);  
  30.   };  

Here we have used the Reactive form. In this whenever we use the reactive forms every field is considered as observable we can subscribe to that field and listen to any changes made to that input value

In the above snippet, we have created the form by using the formcontrol and added to the formgroup. This control has the property valuechanges which always returns the observable. Now, whenever I type the number in the field, I get the square of that number.

Template code can be like below for the above change.

  1. <form [formGroup]="mathform">  
  2.   <input formControlName="inputnumber">  
  3. </form>  
  4. <hr>  
  5. <div>  
  6.   Square of the number is :: <b>{{squaredata}}</b>  
  7. </div>   

The output for the same can be like below.
Angular
Unsubscribing from the Observable

There are chances that we need to unsubscribe from the observable and do some cleanup like resource release. Unsubscribe()  will unhook the members listening to the Observable stream. Also, there is a way to provide the custom call back method OnUnsubscribe() which will be called to manually clean up the things after the subscription has been ended.

Do we need to call unsubscribe every time we call the observables? The answer is no, observables have a built-in ability to dispose of all the resources whenever the Complete or the error method gets called in the application.

Hot and Cold Observables

Generally, there are two types of the observables; the first one is Cold observable and the other one is Hot observable

What are cold observables?

Cold observables are the ones which are explicitly invoked by the producer in our first example where we used the set timeout method we were manually creating and subscribing the observable inside the start functions --  this is cold observable. 

What are hot observables?

In contrast to the cold observable we have hot observables,  which we do while getting the power of the number which is invoked as soon as the value change occurs, it will start subscribing the stream before waiting for the producer to send the signal to subscribe.

So, this was all about the observables. In the next article, we will see how we can use the observable with the HttpClient for calling the HTTP method and how we can transform the result and get the error.

Source code for the same can be found on this Link

References

  1. https://hackernoon.com/understanding-creating-and-subscribing-to-observables-in-angular-426dbf0b04a3
  2. https://rangle.io/