Friday, September 11, 2020

How to Create a Custom Observable in Angular

In this post we’ll see how to create a custom Observable in Angular. Observables are based on Observer design pattern in which an object, called the subject, maintains a list of observers and notifies them automatically of state changes. Some thing like this-

public interface Subject {
  public void register(Observer obj);
  public void unregister(Observer obj);

  public void notifyObservers();
}

Steps to create custom observable in Angular

1. First thing is to create an instance of Observable for which you can use Observable.create() method. This created observable instance defines a subscriber function. The subscriber function defines how to obtain or generate values to be published. This is the function that is executed when a consumer calls the subscribe() method.

2. An observable can send three types of notifications-

  • next- This even emits the next value from the Observable.
  • error- Notification for an error in Observable. An error halts execution of the observable instance.
  • complete- Notifies that the execution of Observable is completed.

The subscriber function you will define with in Observable.create() takes an observer object that defines callback methods to handle the three types of notifications mentioned above. Something similar to this structure-

Observable.create(observer => {
	observer.next();
	observer.error();
	observer.complete();
});

3. An Observable instance begins publishing values only when someone subscribes to it. You subscribe by calling the subscribe() method of the Observable instance, passing an observer object to receive the notifications.

Creating custom observable Angular example

Custom observable is created in the app.component.ts file. Created observable asynchronously sends a random number between 0-9.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'], 
})
export class AppComponent implements OnInit{
  ngOnInit() {
    const customObservable = Observable.create((observer: Observer<Number>) => {
      setInterval(
        () => {
          observer.next(Math.floor(Math.random() * 10));
        }, 1000);
    });

    customObservable.subscribe((data: Number) => {
      console.log("Next Number: " + data)
    });
  }
}

Some of the important points to note here are-

  1. Observable instance is created using Observable.create() method with in which you will have an asynchronous function to generate value. That function’s parameter is an Observer object.
  2. setInterval method is also used here which allows us to run a function repeatedly.
  3. next method emits the next generated random number.
  4. You subscribe to an observable instance using the subscribe() method.
  5. With in the subscribe() method there is an anonymous function which receives the data from observable. In this example that data is just logged on the console.

app.component.html

<h4>Custom Observable example</h4>
Custom Observable Angular

Observable notification methods error and complete

In the above example only next() method is used but there are two other notifications an observable can send- error and complete. We’ll add those two too with some condition which results in those notifications being generated.

If error event is raised the Observable stops emitting any further events and terminates. Even the complete event is not emitted in case of error.

In the subscribe() method now there are three anonymous functions for three types of events. In case of complete no data is emitted so the function in subscribe() method that corresponds to complete even has no parameter.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'], 
})
export class AppComponent implements OnInit{
  ngOnInit() {
    const customObservable = Observable.create((observer: Observer<Number>) => {
      setInterval(
        () => {
          let randomNumber = Math.floor(Math.random() * 10);
          if(randomNumber == 8){
            observer.error("Error while generating random number");
          } else if(randomNumber == 9){
            observer.complete();
          }else {
            observer.next(randomNumber);
          }
        }, 1000);
    });

    customObservable.subscribe((data: Number) => {
      console.log("Next Number: " + data);
    }, error => {
      console.log(error);
    }, ()=>{
      console.log("Observable Completed");
    }
    );
  }
}
Create custom observable

That's all for this topic How to Create a Custom Observable in Angular. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular Cross Component Communication Using Subject Observable
  2. Service in Angular With Examples
  3. Angular Routing Concepts With Example
  4. Forms in Angular
  5. Angular CanActivateChild Guard to protect Child Routes

You may also like-

  1. Angular Route Resolver - Passing Data Dynamically
  2. Highlight Currently Selected Menu Item Angular Routing Example
  3. Custom Validator in Angular Reactive Form
  4. Angular ngFor Directive With Examples
  5. PriorityBlockingQueue in Java Concurrency
  6. Abstract Class in Java
  7. Java Program to Detect And Remove Loop in a Linked List
  8. BeanFactoryPostProcessor in Spring Framework

No comments:

Post a Comment