[RxJS] Execute tasks asynchronously with Async Scheduler

The asyncScheduler lets you schedule tasks asynchronously, similar to a setTimeout. 

All schedulers have a signature of work, delay, state, but provding a delay for any other schedular will simply default it to the asyncSceduler behind the scenes.

The schedule call returns a subscription, so if you need to cancel work before it is performed you can simply unsubscribe, similar to observables.

const sub = asyncScheduler.schedule(
  // work
  console.log,
  // delay
  2000,
  //state
  'Hello World!'
)
// sub.unsubscribe();

 

Most static creation operators accepts a scheduler as the last argument. For instance, if we want to emit values from of() asynchronously, we can supply the asyncScheduler as the last argument.

of(1, 2, 3, asyncScheduler).subscribe(observer);
of(4, 5, 6).subscribe(observer);
/* 4,5,6,1,2,3*/

 

You can also introduce schedulers by using the observeOn operator. This is equivalent to wrapping next, error, and complete functions in appropriate scheduler.

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

const observer = {
  next: (val) => console.log('next', val),
  error: (err) => console.log('error', err),
  complete: () => console.log('complete'),
};

of(1,2,3)
  .pipe(
    tap((val) => console.log('first tap', val)),
    // can add delay as second arguement
    observeOn(asyncScheduler, 2000),
    tap((val) => console.log('second tap', val))
  ).subscribe(observer);
/*
first tap 1
first tap 2
first tap 3
second tap 1
next 1
second tap 2
next 2
second tap 3
next 3
complete
*/

 

Lastly, you can use schedulers to determine when subscriptions occur by using the subscribeOn operator. This is equivalent to wrapping your entire subscription in a scheduler.
of(1, 2, 3).pipe(tap(observer), subscribeOn(asyncScheduler, 2000));
 .subscribe(observer);

/*
from tap 1
next 1
from tap 2
next 2
from tap 3
next 3
complete
*/

 

posted @ 2022-10-03 14:01  Zhentiw  阅读(35)  评论(0编辑  收藏  举报