Observable Demo

  • In this example we create a Custom Observable and subscribe to it.

Create a new Project in Angular

ng new ObservablesDemo

Change content of app.component.html as below :

This program prints the observale values in the console

Change the content of app.component.ts as below :

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable  } from 'rxjs/Observable';
import { Observer  } from 'rxjs/Observer';
import 'rxjs';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  title = 'ObservablesDemo';
  customObsSubscription: Subscription;
  constructor(){ }

  ngOnInit(){
    const myObservable = Observable.create((observer: Observer<string>) => {
      setTimeout(() => observer.next('first package'), 2000);
      setTimeout(() => observer.next('second package'), 4000);
      //setTimeout(() => observer.error('This does not work'), 5000);
      setTimeout(() => observer.complete(), 7000);
      setTimeout(() => observer.next('third package package'), 4000);//Third package never arrives
    });
    this.customObsSubscription = myObservable.subscribe(
      (data: string) => {console.log('Data : '+data); },
      (error: string) => {console.log('Error : '+error); },
      () => {console.log('Completed'); }
    );
  }
  ngOnDestroy(): void {
    this.customObsSubscription.unsubscribe();
  }
}

Now execute the project and check the console :

Leave a Comment