| 1 |
import { MonoTypeOperatorFunction, SchedulerLike } from '../types'; |
| 2 |
import { operate } from '../util/lift'; |
| 3 |
|
| 4 |
/** |
| 5 |
* Asynchronously subscribes Observers to this Observable on the specified {@link SchedulerLike}. |
| 6 |
* |
| 7 |
* With `subscribeOn` you can decide what type of scheduler a specific Observable will be using when it is subscribed to. |
| 8 |
* |
| 9 |
* Schedulers control the speed and order of emissions to observers from an Observable stream. |
| 10 |
* |
| 11 |
*  |
| 12 |
* |
| 13 |
* ## Example |
| 14 |
* |
| 15 |
* Given the following code: |
| 16 |
* |
| 17 |
* ```ts |
| 18 |
* import { of, merge } from 'rxjs'; |
| 19 |
* |
| 20 |
* const a = of(1, 2, 3); |
| 21 |
* const b = of(4, 5, 6); |
| 22 |
* |
| 23 |
* merge(a, b).subscribe(console.log); |
| 24 |
* |
| 25 |
* // Outputs |
| 26 |
* // 1 |
| 27 |
* // 2 |
| 28 |
* // 3 |
| 29 |
* // 4 |
| 30 |
* // 5 |
| 31 |
* // 6 |
| 32 |
* ``` |
| 33 |
* |
| 34 |
* Both Observable `a` and `b` will emit their values directly and synchronously once they are subscribed to. |
| 35 |
* |
| 36 |
* If we instead use the `subscribeOn` operator declaring that we want to use the {@link asyncScheduler} for values emitted by Observable `a`: |
| 37 |
* |
| 38 |
* ```ts |
| 39 |
* import { of, subscribeOn, asyncScheduler, merge } from 'rxjs'; |
| 40 |
* |
| 41 |
* const a = of(1, 2, 3).pipe(subscribeOn(asyncScheduler)); |
| 42 |
* const b = of(4, 5, 6); |
| 43 |
* |
| 44 |
* merge(a, b).subscribe(console.log); |
| 45 |
* |
| 46 |
* // Outputs |
| 47 |
* // 4 |
| 48 |
* // 5 |
| 49 |
* // 6 |
| 50 |
* // 1 |
| 51 |
* // 2 |
| 52 |
* // 3 |
| 53 |
* ``` |
| 54 |
* |
| 55 |
* The reason for this is that Observable `b` emits its values directly and synchronously like before |
| 56 |
* but the emissions from `a` are scheduled on the event loop because we are now using the {@link asyncScheduler} for that specific Observable. |
| 57 |
* |
| 58 |
* @param scheduler The {@link SchedulerLike} to perform subscription actions on. |
| 59 |
* @param delay A delay to pass to the scheduler to delay subscriptions |
| 60 |
* @return A function that returns an Observable modified so that its |
| 61 |
* subscriptions happen on the specified {@link SchedulerLike}. |
| 62 |
*/ |
| 63 |
export function subscribeOn<T>(scheduler: SchedulerLike, delay: number = 0): MonoTypeOperatorFunction<T> { |
| 64 |
return operate((source, subscriber) => { |
| 65 |
subscriber.add(scheduler.schedule(() => source.subscribe(subscriber), delay)); |
| 66 |
}); |
| 67 |
} |