| 1 |
import { OperatorFunction, ObservableInput, ObservedValueOf } from '../types'; |
| 2 |
import { switchMap } from './switchMap'; |
| 3 |
import { identity } from '../util/identity'; |
| 4 |
|
| 5 |
/** |
| 6 |
* Converts a higher-order Observable into a first-order Observable |
| 7 |
* producing values only from the most recent observable sequence |
| 8 |
* |
| 9 |
* <span class="informal">Flattens an Observable-of-Observables.</span> |
| 10 |
* |
| 11 |
*  |
| 12 |
* |
| 13 |
* `switchAll` subscribes to a source that is an observable of observables, also known as a |
| 14 |
* "higher-order observable" (or `Observable<Observable<T>>`). It subscribes to the most recently |
| 15 |
* provided "inner observable" emitted by the source, unsubscribing from any previously subscribed |
| 16 |
* to inner observable, such that only the most recent inner observable may be subscribed to at |
| 17 |
* any point in time. The resulting observable returned by `switchAll` will only complete if the |
| 18 |
* source observable completes, *and* any currently subscribed to inner observable also has completed, |
| 19 |
* if there are any. |
| 20 |
* |
| 21 |
* ## Examples |
| 22 |
* |
| 23 |
* Spawn a new interval observable for each click event, but for every new |
| 24 |
* click, cancel the previous interval and subscribe to the new one |
| 25 |
* |
| 26 |
* ```ts |
| 27 |
* import { fromEvent, tap, map, interval, switchAll } from 'rxjs'; |
| 28 |
* |
| 29 |
* const clicks = fromEvent(document, 'click').pipe(tap(() => console.log('click'))); |
| 30 |
* const source = clicks.pipe(map(() => interval(1000))); |
| 31 |
* |
| 32 |
* source |
| 33 |
* .pipe(switchAll()) |
| 34 |
* .subscribe(x => console.log(x)); |
| 35 |
* |
| 36 |
* // Output |
| 37 |
* // click |
| 38 |
* // 0 |
| 39 |
* // 1 |
| 40 |
* // 2 |
| 41 |
* // 3 |
| 42 |
* // ... |
| 43 |
* // click |
| 44 |
* // 0 |
| 45 |
* // 1 |
| 46 |
* // 2 |
| 47 |
* // ... |
| 48 |
* // click |
| 49 |
* // ... |
| 50 |
* ``` |
| 51 |
* |
| 52 |
* @see {@link combineLatestAll} |
| 53 |
* @see {@link concatAll} |
| 54 |
* @see {@link exhaustAll} |
| 55 |
* @see {@link switchMap} |
| 56 |
* @see {@link switchMapTo} |
| 57 |
* @see {@link mergeAll} |
| 58 |
* |
| 59 |
* @return A function that returns an Observable that converts a higher-order |
| 60 |
* Observable into a first-order Observable producing values only from the most |
| 61 |
* recent Observable sequence. |
| 62 |
*/ |
| 63 |
export function switchAll<O extends ObservableInput<any>>(): OperatorFunction<O, ObservedValueOf<O>> { |
| 64 |
return switchMap(identity); |
| 65 |
} |