首页 > 其他分享 >[RxJS] Execute tasks asynchronously with Async Scheduler

[RxJS] Execute tasks asynchronously with Async Scheduler

时间:2022-10-03 14:11:09浏览次数:51  
标签:Execute tasks tap asyncScheduler observer next Scheduler console log

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
*/

 

标签:Execute,tasks,tap,asyncScheduler,observer,next,Scheduler,console,log
From: https://www.cnblogs.com/Answer1215/p/16750462.html

相关文章