RxJS - Working with Scheduler


Advertisements

A scheduler controls the execution of when the subscription has to start and notified.

To make use of scheduler we need the following −

import { Observable, asyncScheduler } from 'rxjs';
import { observeOn } from 'rxjs/operators';

Here is a working example, wherein, we will use the scheduler that will decide the execution.

Example

import { Observable, asyncScheduler } from 'rxjs';
import { observeOn } from 'rxjs/operators';

var observable = new Observable(function subscribe(subscriber) {
   subscriber.next("My First Observable");
   subscriber.next("Testing Observable");
   subscriber.complete();
}).pipe(
   observeOn(asyncScheduler)
);
console.log("Observable Created");
observable.subscribe(
   x => console.log(x),
   (e)=>console.log(e),
   ()=>console.log("Observable is complete")
);

console.log('Observable Subscribed');

Output

Scheduler

Without scheduler the output would have been as shown below −

Scheduler Controls
Advertisements