lookout.devlookout.dev
search
Share Knowledge
71

Rxjs operators: scan vs. reduce

Thursday, October 29, 2020

The scan and reduce RxJS operators are two very similar operators that work very much like the reduce() method of arrays.

The difference is an observable created with scan will emit on each source emission, whereas reduce will emit only once on completion.

Code Examples

scan-vs-reduce

const source$ = interval(1000).pipe(take(4));
// source$: -0-1-2-(3|)

const usingScan$ = source$.pipe(scan(
  (acc, curr) => acc + curr,
  0 
));
// usingScan$: -0-1-3-(6|)

const usingReduce$ = source$.pipe(reduce(
  (acc, curr) => acc + curr,
  0
));
// usingReduce$: -------(6|)
Zack DeRose

Have a question or comment?