Learn RxJS
Search…
concatMapTo

signature: concatMapTo(observable: Observable, resultSelector: function): Observable

Subscribe to provided observable when previous completes, emit values.

Examples

Example 1: Map to basic observable (simulating request)
1
// RxJS v6+
2
import { of, interval } from 'rxjs';
3
import { concatMapTo, delay, take } from 'rxjs/operators';
4
5
//emit value every 2 seconds
6
const sampleInterval = interval(500).pipe(take(5));
7
const fakeRequest = of('Network request complete').pipe(delay(3000));
8
//wait for first to complete before next is subscribed
9
const example = sampleInterval.pipe(concatMapTo(fakeRequest));
10
//result
11
//output: Network request complete...3s...Network request complete'
12
const subscribe = example.subscribe(val => console.log(val));
Copied!
Example 2: Using projection with concatMap
1
// RxJS v6+
2
import { interval } from 'rxjs';
3
import { concatMapTo, take } from 'rxjs/operators';
4
//emit value every 2 seconds
5
const interval$ = interval(2000);
6
//emit value every second for 5 seconds
7
const source = interval(1000).pipe(take(5));
8
/*
9
***Be Careful***: In situations like this where the source emits at a faster pace
10
than the inner observable completes, memory issues can arise.
11
(interval emits every 1 second, basicTimer completes every 5)
12
*/
13
// basicTimer will complete after 5 seconds, emitting 0,1,2,3,4
14
const example = interval$.pipe(
15
concatMapTo(
16
source,
17
(firstInterval, secondInterval) => `${firstInterval} ${secondInterval}`
18
)
19
);
20
/*
21
output: 0 0
22
0 1
23
0 2
24
0 3
25
0 4
26
1 0
27
1 1
28
continued...
29
30
*/
31
const subscribe = example.subscribe(val => console.log(val));
Copied!

Additional Resources

Last modified 1yr ago