Learn RxJS
Search…
mergeScan

signature: mergeScan(accumulator: (acc, value, index: number) => ObservableInput, seed, concurrent: number = Number.POSITIVE_INFINITY): OperatorFunction

Accumulate value over time via merged observables.

Examples

Example 1: Accumulate total duration mouse held down over time
1
// RxJS v6+
2
import { fromEvent, interval } from 'rxjs';
3
import { mergeScan, take, takeUntil, map, scan } from 'rxjs/operators';
4
5
// reference
6
const durationElem = document.getElementById('duration');
7
8
// streams
9
const mouseDown$ = fromEvent(document, 'mousedown');
10
const mouseUp$ = fromEvent(document, 'mouseup');
11
12
// accumulate time mouse held down over time
13
mouseDown$
14
.pipe(
15
mergeScan((acc, curr) => {
16
return interval(1000).pipe(
17
scan((a, _) => ++a, 0),
18
map((val: any) => val + acc),
19
takeUntil(mouseUp$)
20
);
21
}, 0)
22
// output: 1s...2s...3s...4s...
23
)
24
.subscribe(val => (durationElem.innerHTML = `${val}s`));
Copied!

Additional Resources

  • pluck 📰 -
    Official docs