Sunday, August 23, 2020

Creating Observable

We can create our own Observable by creating a function that takes an observer parameter. The function will be passed to create the Observable. When someone subscribes to the observable, the function is called and returns the values emitted from the function.

In the below sample we create a function listGenerator, which takes an observer as a parameter and emit list values one at a time using .next().

Next we create a new observable listSubscriber and pass the listGenerator function as parameter. When we subscribe to this observable this functions will be called and the values emitted by the functions are returned in sequence to the subscribed function. 

import { Component, OnInit } from '@angular/core';
import { Observable, Observer } from 'rxjs';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  currentTime$
  ngOnInit() {
    const listSubscriber = new Observable(listGenerator);
    //
    listSubscriber.subscribe({
      next(item) { console.log(item); },
      complete() { console.log('Observable iteration completed'); }
    });
  }
}
function listGenerator(observer) { 
  observer.next("Item - 1");
  observer.next("Item - 2");
  observer.next("Item - 3");
  observer.complete(); 
  return {unsubscribe() {}};
}

When we subscribe to the observable and invoke its next() function, it will return each item in the collection one at a time till all the items are returned. We print the value returned to the console.


Output




Search Flipkart Products:
Flipkart.com

No comments: