Learn RxJS
Search…
switchMapTo

signature: switchMapTo(innerObservable: Observable, resultSelector: function(outerValue, innerValue, outerIndex, innerIndex): any): Observable

Map to same inner observable, complete previous inner observable.

πŸ’‘ If you need to consider the emitted value from the source, try switchMap!
​​
​
​

Examples

Example 1: Restart countdown on click, until countdown completes one time
1
// RxJS v6+
2
import { interval, fromEvent } from 'rxjs';
3
import {
4
switchMapTo,
5
scan,
6
startWith,
7
takeWhile,
8
finalize
9
} from 'rxjs/operators';
10
​
11
const COUNTDOWN_TIME = 10;
12
​
13
// reference
14
const countdownElem = document.getElementById('countdown');
15
​
16
// streams
17
const click$ = fromEvent(document, 'click');
18
const countdown$ = interval(1000).pipe(
19
scan((acc, _) => --acc, COUNTDOWN_TIME),
20
startWith(COUNTDOWN_TIME)
21
);
22
​
23
click$
24
.pipe(
25
switchMapTo(countdown$),
26
takeWhile(val => val >= 0),
27
finalize(() => (countdownElem.innerHTML = "We're done here!"))
28
)
29
.subscribe((val: any) => (countdownElem.innerHTML = val));
Copied!

Additional Resources

Last modified 1yr ago