Learn RxJS
Search…
merge

signature: merge(input: Observable): Observable

Turn multiple observables into a single observable.

πŸ’‘ This operator can be used as either a static or instance method!
πŸ’‘ If order not throughput is a primary concern, try concat instead!
​​
​
​

Examples

Example 1: merging multiple observables, static method
1
// RxJS v6+
2
import { mapTo } from 'rxjs/operators';
3
import { interval, merge } from 'rxjs';
4
​
5
//emit every 2.5 seconds
6
const first = interval(2500);
7
//emit every 2 seconds
8
const second = interval(2000);
9
//emit every 1.5 seconds
10
const third = interval(1500);
11
//emit every 1 second
12
const fourth = interval(1000);
13
​
14
//emit outputs from one observable
15
const example = merge(
16
first.pipe(mapTo('FIRST!')),
17
second.pipe(mapTo('SECOND!')),
18
third.pipe(mapTo('THIRD')),
19
fourth.pipe(mapTo('FOURTH'))
20
);
21
//output: "FOURTH", "THIRD", "SECOND!", "FOURTH", "FIRST!", "THIRD", "FOURTH"
22
const subscribe = example.subscribe(val => console.log(val));
Copied!
Example 2: merge 2 observables, instance method
1
// RxJS v6+
2
import { merge } from 'rxjs/operators';
3
import { interval } from 'rxjs';
4
​
5
//emit every 2.5 seconds
6
const first = interval(2500);
7
//emit every 1 second
8
const second = interval(1000);
9
//used as instance method
10
const example = first.pipe(merge(second));
11
//output: 0,1,0,2....
12
const subscribe = example.subscribe(val => console.log(val));
Copied!

Additional Resources

Last modified 6mo ago