RxJS subscribeOn
异步地在指定上将 Observable 订阅此 Observable SchedulerLike。
subscribeOn<T>(scheduler: SchedulerLike, delay: number = 0): MonoTypeOperatorFunction<T>
参量
| 调度器 | 在 SchedulerLike上执行订阅操作。 |
|---|---|
| 延迟 | 可选的。默认值为0。类型:number。 |
returns
MonoTypeOperatorFunction<T>:对源 Observable 进行了修改,使其订阅发生在指定的SchedulerLike。。
描述
subscribeOn您可以使用它来确定特定 Observable 订阅时将使用哪种调度程序。
调度程序控制可观察流向观察者的发射速度和顺序。

例
给出以下代码:
import { of, merge } from 'rxjs';
const a = of(1, 2, 3, 4);
const b = of(5, 6, 7, 8, 9);
merge(a, b).subscribe(console.log);
一旦被观察到a,这两个 Observable b 都会直接并同步地发出它们的值。这将导致输出1 2 3 4 5 6 7 8 9。
但是,如果改为使用subscribeOn运算符,则声明要使用async发出的值a:
import { of, merge, asyncScheduler } from 'rxjs';
import { subscribeOn } from 'rxjs/operators';
const a = of(1, 2, 3, 4).pipe(subscribeOn(asyncScheduler));
const b = of(5, 6, 7, 8, 9);
merge(a, b).subscribe(console.log);
输出将改为5 6 7 8 9 1 2 3 4。这是因为 Observable b 像以前一样直接且同步地发出其值,但从a该事件发出的消息已安排在事件循环