subscribeOn
function stable
Asynchronously subscribes Observers to this Observable on the specified SchedulerLike.
subscribeOn<T>(scheduler: SchedulerLike, delay: number = 0): MonoTypeOperatorFunction<T>
Parameters
| scheduler | The |
| delay | Optional. Default is A delay to pass to the scheduler to delay subscriptions |
Returns
MonoTypeOperatorFunction<T>: A function that returns an Observable modified so that its subscriptions happen on the specified SchedulerLike.
Description
With subscribeOn you can decide what type of scheduler a specific Observable will be using when it is subscribed to.
Schedulers control the speed and order of emissions to observers from an Observable stream.
Example
Given the following code:
import { of, merge } from 'rxjs';
const a = of(1, 2, 3);
const b = of(4, 5, 6);
merge(a, b).subscribe(console.log);
// Outputs
// 1
// 2
// 3
// 4
// 5
// 6 Both Observable a and b will emit their values directly and synchronously once they are subscribed to.
If we instead use the subscribeOn operator declaring that we want to use the asyncScheduler for values emited by Observable a:
import { of, merge, asyncScheduler } from 'rxjs';
import { subscribeOn } from 'rxjs/operators';
const a = of(1, 2, 3).pipe(subscribeOn(asyncScheduler));
const b = of(4, 5, 6);
merge(a, b).subscribe(console.log);
// Outputs
// 4
// 5
// 6
// 1
// 2
// 3 The reason for this is that Observable b emits its values directly and synchronously like before but the emissions from a are scheduled on the event loop because we are now using the asyncScheduler for that specific Observable.
© 2015–2021 Google, Inc., Netflix, Inc., Microsoft Corp. and contributors.
Code licensed under an Apache-2.0 License. Documentation licensed under CC BY 4.0.
https://rxjs.dev/api/operators/subscribeOn