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