RxJS: Reduce vs Scan

ippatev

Aleksandr Ippatev

Posted on August 10, 2021

RxJS: Reduce vs Scan

Reduce operator - reduces the values from source observable to a single value that's emitted when the source completes

// RxJS v6+
import { of } from 'rxjs';
import { reduce } from 'rxjs/operators';

const source = of(1, 2, 3, 4);
const example = source.pipe(reduce((acc, val) => acc + val));
//output: Sum: 10
const subscribe = example.subscribe(val => console.log('Sum:', val));
Enter fullscreen mode Exit fullscreen mode

Scan operator - reduce over time!

// RxJS v6+
import { of } from 'rxjs';
import { scan } from 'rxjs/operators';

const source = of(1, 2, 3);
// basic scan example, sum over time starting with zero
const example = source.pipe(scan((acc, curr) => acc + curr, 0));
// log accumulated values
// output: 1,3,6
const subscribe = example.subscribe(val => console.log(val));
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
ippatev
Aleksandr Ippatev

Posted on August 10, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

RxJS: Reduce vs Scan
rxjs RxJS: Reduce vs Scan

August 10, 2021

A simple Countdown with RxJS
rxjs A simple Countdown with RxJS

September 19, 2019

Infinite Scroll con Rxjs
rxjs Infinite Scroll con Rxjs

September 18, 2019

Polling using RxJS
rxjs Polling using RxJS

September 10, 2018