Web Programming TutorialsLearn the Difference between cold and hot Observables in Angular 2

Learn the Difference between cold and hot Observables in Angular 2

observables

In this article, we are going to explore one of the new concepts of Angular 2, which is the use of Observables. It is known to be a projected feature for ES2016 (i.e. ES7). Here, first we will discuss the Observables with the help of a basic example and later in this article, we will outline the differences between the cold and hot Observables.

What are Observables in Angular 2?
Observables in Angular 2 are used for asynchronous data management. They are capable of emitting multiples values over a period of time. They differ from Promises in a way that the former can emit different values but the latter can return either one value or one error when called. Therefore, the Observables are great as long as we have multiple values over time. Observables have use in Angular 2 for the new HTTP service and the EventEmitter system as they require multiple values to be emitted over any given period of time.

A basic Observables in Angular 2
We are going to develop an app in Angular2 by using Observables which emit different values depending on the set timeouts (period of time). The following is the app structure for this app in Angular 2.0.

  • app/main.ts
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app-module';

platformBrowserDynamic().bootstrapModule(AppModule);

Explanation of Code:
The above main.ts file is used to Bootstrap the angular 2.0 app that uses the root component from the NgModule.

  • app/app-module.ts
import { BrowserModule }  from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app-component';

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})

export class AppModule {

}

Explanation of Code:
The root App Module typescript file is present in the app package. Here, we are importing the NgModule, BrowserModule, and AppComponent classes shown above. The @NgModule decorator is declared here that has the import, declaration and bootstrap class to start the app.

  • app/app-component.ts
import {Component} from '@angular/core';
import {Observable} from 'rxjs/Observable';

@Component({
	selector: 'observable-app-demo',
	templateUrl: 'resource/app-component.html',
	styleUrls: ['assets/styles.css'] 
})
export class AppComponent {
  
  private source: Observable<Array<number>>;
  private values: Array<number> = [];
  private anyErrorObtained: boolean;
  private isEnded: boolean;

  constructor() {
  }
  
  start() {
      this.source = new Observable(observer => {
          setTimeout(() => {
              observer.next(Date.now());
          }, 1000);
          
          setTimeout(() => {
              observer.next(Date.now());
          }, 2000);
            
          setTimeout(() => {
              observer.next(Date.now());
          }, 3000);
          
          setTimeout(() => {
              observer.complete();
          }, 4000);
      });

      let subscription = this.source.subscribe(
          value => this.values.push(value),
          error => this.anyErrorObtained = true,
          () => this.isEnded = true
      );
  }

}

Explanation of Code:
It has the selector ‘observable-app-demo’ which is used on the index.html to load the complete app on the browser. It has the template URL as ‘resource/app-component.html’ and styleUrls as ‘assets/styles.css’ as shown below. In the controller class ‘AppComponent’, we have defined a constructor and function ‘start ()’. The ‘start ()’ function has all the logic for the implementation of the Observable where we are instantiating Observable and setting the value of current date (i.e. Date.now ()) at the time period of 1000, 2000 and 3000 as shown above.

  • resource/app-component.html
<div align="center">

	<h2>A basic Observables demo in Angular 2</h2>

	<h3 style="margin-bottom: 0">VALUES:</h3>
	<div *ngFor="let value of values"> {{ value }}</div>

	<h3 style="margin-bottom: 0">Error Obtained:</h3>
	<div>Error Obtained: {{anyErrorObtained}}</div>

	<h3 style="margin-bottom: 0">Status as Finished:</h3>
	<div>Ended: {{ isEnded }}</div>

	<button style="margin-top: 2rem;" (click)="start()">Start</button>

</div>
<br>
<hr>

Explanation of Code:
It is the HTML code template for ‘app-component-ts’. Here, we are using ‘*ngFor’ directive to iterate over the values array and in the next two headings, we are displaying the ‘anyErrorObtained’ and ‘isEnded’ status which are of Boolean data type.

  • assets/styles.css
h1, h2, h3 {
  color: #ty4;
  font-family: Arial, Helvetica, sans-serif;
  font-weight: lighter;
}
body, input[text], button {
  color: #588;
  font-family: sans-serif;
  -ms-text-size-adjust: 100%;
  -webkit-text-size-adjust: 100%;
}
a {
  cursor: pointer;
  cursor: hand;
}
button {
  font-family: Arial;
  background-color: #eee;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  cursor: hand;
}
button:hover {
  background-color: #cmh8dc;
}
button:disabled {
  background-color: #eee;
  color: #ava;
  cursor: auto;
}
nav a {
  padding: 5px 10px;
  text-decoration: none;
  margin-top: 10px;
  display: inline-block;
  background-color: #eee;
  border-radius: 4px;
}
nav a:visited, a:link {
  color: #607D8B;
}
nav a:hover {
  color: #039be5;
  background-color: #CFD8DC;
}
nav a.active {
  color: #039be5;
}
/* everywhere else */
* {
  font-family: Arial, Helvetica, sans-serif;
}

Explanation of Code:
This is the stylesheet used to style the text on the web page of the app.

  • Index.html
<html>
<head>
<title>Custom form Controls Angular 2.0</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="assets/styles.css">
<!-- 1. Load libraries -->
<!-- Poly-fills for the older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<link rel="stylesheet" 
      href="node_modules/bootstrap/dist/css/bootstrap.min.css">
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
      System.import('app').catch(
    		  function(err){ 
    			  console.error(err); 
    			  }
    		  );
</script>
</head>
<!-- 3. Display the application -->
<body>
		<observable-app-demo>A moment please...</observable-app-demo>
</body>
</html>

Explanation of Code:
This is the ‘index.html’ file that has the ‘observable-app-demo’ tag in its body section i.e. selector defined in the ‘app-component’ to load and display the complete application. Here, we are include all the paths for the scripts which are required for the Angular 2.0 build as shown above.

Output
When we run the above angular 2.0 model-driven form app by executing the command ‘npm start’ on command line that has pointer to the application’s root directory ‘angular2-observables’, then we will observe the following output.
image1

Differences between Cold and Hot Observables
Cold observables are the ones that start running upon subscription i.e. in other words the values are pushed to the observers by the observable sequence only when we call Subscribe. Whereas, the hot observables are already producing values even before the subscription is made active e.g. returning value on a mouse move event, etc. is an example of hot Observables. Therefore, a hot observer is one which keeps on publishing values irrespective of someone listening to it or not unlike a cold observable which are lazy and start producing or publishing values when required by someone during a subscription call. The Http service in Angular 2.0 is an example of cold observables.

For Source Code in Cold and Hot Observables

Conclusion
In this article, we have built a basic Observable app in Angular 2.0 to demonstrate the working of this new feature in Angular 2.0. Later, we outlined the differences between the cold and hot Observables.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -