💡 This operator can be used as either a static or instance method!
💡 If order not throughput is a primary concern, try concat instead!
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { mapTo } from 'rxjs/operators';
import { interval, merge } from 'rxjs';
//emit every 2.5 seconds
const first = interval(2500);
//emit every 2 seconds
const second = interval(2000);
//emit every 1.5 seconds
const third = interval(1500);
//emit every 1 second
const fourth = interval(1000);
//emit outputs from one observable
const example = merge(
first.pipe(mapTo('FIRST!')),
second.pipe(mapTo('SECOND!')),
third.pipe(mapTo('THIRD')),
fourth.pipe(mapTo('FOURTH'))
);
//output: "FOURTH", "THIRD", "SECOND!", "FOURTH", "FIRST!", "THIRD", "FOURTH"
const subscribe = example.subscribe(val => console.log(val));
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { merge } from 'rxjs/operators';
import { interval } from 'rxjs';
//emit every 2.5 seconds
const first = interval(2500);
//emit every 1 second
const second = interval(1000);
//used as instance method
const example = first.pipe(merge(second));
//output: 0,1,0,2....
const subscribe = example.subscribe(val => console.log(val));
- merge 📰 - Official docs
- merge - In Depth Dev Reference
- Handling multiple streams with merge 🎥 💵 - John Linquist
- Sharing network requests with merge 🎥 💵 - André Staltz
- Combination operator: merge 🎥 💵 - André Staltz
- Build your own merge operator 🎥 - Kwinten Pisman
📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/merge.ts