Contents

mergeAll operator in RxJs

mergeAll Operator

Can be imported from here:

1
2
3
import { mergeAll } from 'rxjs/operators';
// or
const { mergeAll } = require('rxjs/operators');

For official documentation, visit https://rxjs-dev.firebaseapp.com/api/operators/mergeAll

Converts higher order observable into first order observable which concurrently emits values emitted by inner observable.

1
2
3
4
5
6
7
import { fromEvent, interval } from 'rxjs';
import { map, mergeAll, take } from 'rxjs/operators';

const clicks = fromEvent(document, 'click');
const higherOrder = clicks.pipe(map((ev) => interval(1000).pipe(take(5))));
const firstOrder = higherOrder.pipe(mergeAll());
firstOrder.subscribe(x => console.log(x));
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# click
0
1
2
# click
3
0
4
1
2
3
4
/rxjs/mergeAll.svg
mergeAll() Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import { take, map, mergeAll } from 'rxjs/operators';
import { interval, from } from 'rxjs';

const array1 = ['a', 'b', 'c',];
const array2 = [1, 2, 3];


const ob1$ = interval(2000).pipe(take(array1.length), map((i) => array1[i]));
const ob2$ = interval(1000).pipe(take(array2.length), map((i) => array2[i]));

const observableOfObservables$ = from([ob1$, ob2$]);

const result$ = observableOfObservables$.pipe(mergeAll());
1
2
3
4
5
6
1
a
2
3
b
c

Note: mergeAll(4)

1
2
3
4
5
6
7
8
9
import { fromEvent, interval } from 'rxjs';
import { take, map, mergeAll } from 'rxjs/operators';

const clicks = fromEvent(document, 'click');
const higherOrder = clicks.pipe(
  map((ev) => interval(500).pipe(take(3))),
);
const firstOrder = higherOrder.pipe(mergeAll(4));
firstOrder.subscribe(x => console.log(x));
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# click click click click (fast)
0
0
0
0
1
1
1
1
2
2
2
2

Комментарии