bluehost-banner
How to create Custom Observable - RXJS

How to create Custom Observable - RXJS

In this article, we will look at the many different methods of creating Observables provided to us by RxJS.

Observables are the foundation of RxJS.

There are two main methods to create Observables in RxJS. Subjects and Operators. We will take a look at both of these!

What is an Observable?

Observables are like functions with zero arguments that push multiple values to their Observers, either synchronously or asynchronously.

Also read, What Is Observable In RxJS

Creating Custom Observable

First, we need to import it from rxjs:

import { Observable } from "rxjs/Observable";

Creating Custom Observable:

// Creating Observable
const obs$ = Observable.create((observer) => {
  observer.next(1);
  observer.next(2);
  //Will Thorow error
 //observer.error(new Error("Limit Exceed"));
  observer.next(3);
  //To stop execution after 
  observer.complete();
});

//Handle Subscription
custObs1.subscribe(
      (res) => {
        console.log(res);
        this._desingUtility.print(res, "elContainer");
      },
      (error) => {
        this.status = "error";
      },
      () => {
        this.status = "completed";
      }
    );

In the above example, once we subscribe to observable we will start getting observable data, This will appear like below in your browser console:

//OutPut : 
1
2
3

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

You might also like

Leave a Comment