Skip to content
jshacks.dev
Async

The RxJS scan Operator Explained With Examples

Learn how the RxJS scan operator accumulates state over a stream, how it differs from reduce and how to build counters, stores and reducers with it.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Node.js, RabbitMQ, Redis and Apache Kafka logos.

Array code has reduce, which folds a list into one value. A stream has no end to fold toward, so folding it once at the finish would be useless: a click counter that only reports when the user leaves the page helps nobody. scan is the streaming version. It applies an accumulator function to each value and emits the running result every time. Counters, running totals, undo history and whole state stores are all scan over a stream of actions. This post explains scan in RxJS 7 with printed output, shows the seed and its absence, builds a small reducer-based store, contrasts it with reduce and lists the mistakes that cause shared state and surprises.

What it does

scan(accumulator, seed) calls accumulator(acc, value, index) for each source value and emits what it returns. The returned value becomes acc for the next call.

JavaScript
import { of } from "rxjs";
import { scan } from "rxjs/operators";

of(1, 2, 3, 4)
  .pipe(scan((total, n) => total + n, 0))
  .subscribe((total) => console.log(total));
Text
1
3
6
10

Each line is the running total after one more value. The seed 0 is the starting accumulator, and it is not emitted by itself. If you want it as the first output, add startWith(0) after the scan.

Without a seed

If you omit the seed, the first source value becomes the initial accumulator, and the accumulator function is called starting at the second value.

JavaScript
import { of } from "rxjs";
import { scan } from "rxjs/operators";

of(5, 1, 2)
  .pipe(scan((acc, n) => acc + n))
  .subscribe(console.log);
Text
5
6
8

The first value 5 is emitted as it is, and later values are added to it. The seedless form is fine for numbers, but the accumulator type must match the value type. For anything else, pass a seed.

scan versus reduce

reduce emits one value, when the source completes. scan emits on every value.

JavaScript
import { Subject } from "rxjs";
import { reduce, scan } from "rxjs/operators";

const s$ = new Subject();

s$.pipe(scan((a, n) => a + n, 0)).subscribe((v) => console.log("scan", v));
s$.pipe(reduce((a, n) => a + n, 0)).subscribe((v) => console.log("reduce", v));

s$.next(1);
s$.next(2);
s$.next(3);
s$.complete();
Text
scan 1
scan 3
scan 6
reduce 6

On a source that never completes, such as clicks, reduce never emits. That alone decides which to use.

A click counter

JavaScript
import { Subject } from "rxjs";
import { map, scan, startWith } from "rxjs/operators";

const clicks$ = new Subject();

clicks$
  .pipe(
    map(() => 1),
    scan((count, step) => count + step, 0),
    startWith(0)
  )
  .subscribe((count) => console.log(`clicks: ${count}`));

clicks$.next();
clicks$.next();
Text
clicks: 0
clicks: 1
clicks: 2

Building a state store from actions

The pattern behind state libraries is a stream of actions folded by a reducer into a stream of states.

JavaScript
import { Subject } from "rxjs";
import { scan, startWith } from "rxjs/operators";

const initial = { items: [], total: 0 };

function reducer(state, action) {
  switch (action.type) {
    case "add":
      return {
        items: [...state.items, action.item],
        total: state.total + action.item.price,
      };
    case "clear":
      return initial;
    default:
      return state;
  }
}

const actions$ = new Subject();

const state$ = actions$.pipe(scan(reducer, initial), startWith(initial));

state$.subscribe((s) => console.log(s.items.length, s.total));

actions$.next({ type: "add", item: { name: "pen", price: 3 } });
actions$.next({ type: "add", item: { name: "book", price: 12 } });
actions$.next({ type: "clear" });
Text
0 0
1 3
2 15
0 0

The reducer is a pure function, so it can be tested without any streams. The scan supplies the memory. Unknown actions return the same state object, which pairs well with distinctUntilChanged to avoid emitting when nothing changed.

Seeds that are objects: the shared state trap

The seed is one object, reused across subscriptions of the same pipeline definition. If the accumulator mutates it, the mutation survives, and each new subscriber to the same observable can see leftovers.

JavaScript
import { of } from "rxjs";
import { scan } from "rxjs/operators";

const seed = [];

const collected$ = of("a", "b").pipe(
  scan((acc, x) => {
    acc.push(x); // mutates the shared seed
    return acc;
  }, seed)
);

collected$.subscribe((v) => console.log("first", v.length));
collected$.subscribe((v) => console.log("second", v.length));
Text
first 1
first 2
second 3
second 4

The second subscription continued from where the first left off, because both used the same array. Return a new value instead.

JavaScript
import { of } from "rxjs";
import { scan } from "rxjs/operators";

const collected$ = of("a", "b").pipe(
  scan((acc, x) => [...acc, x], [])
);

collected$.subscribe((v) => console.log("first", v.length));
collected$.subscribe((v) => console.log("second", v.length));
Text
first 1
first 2
second 1
second 2

Now each subscriber starts from an empty array, because the old one was never changed. Immutable updates are the safe default. For heavy structures, a library such as Immer can produce the new value without manual spreading.

Windowed history

An accumulator can also forget. Keep only the last three values to build a moving window.

JavaScript
import { of } from "rxjs";
import { scan } from "rxjs/operators";

of(1, 2, 3, 4, 5)
  .pipe(scan((window, n) => [...window, n].slice(-3), []))
  .subscribe((w) => console.log(w.join(",")));
Text
1
1,2
1,2,3
2,3,4
3,4,5

This is the building block for moving averages and "last N events" lists. Compute the average inside a following map.

Async work in the accumulator

The accumulator function is synchronous. If each step needs a promise or an observable, use mergeScan, which lets the accumulator return an observable, or run the async work earlier in the pipe with concatMap and keep scan pure.

JavaScript
import { of } from "rxjs";
import { concatMap, delay, scan } from "rxjs/operators";

of(1, 2, 3)
  .pipe(
    concatMap((n) => of(n * 10).pipe(delay(10))),
    scan((sum, n) => sum + n, 0)
  )
  .subscribe(console.log);
Text
10
30
60

Common mistakes

Mutating the accumulator. It leaks state between subscriptions and breaks change detection. Return new values.

Forgetting the seed type. Without a seed, the first value is the accumulator, and a type mismatch only shows up on the second value.

Expecting the seed to be emitted. It is not. Use startWith for an initial state.

**Using reduce on endless sources.** It never emits. Use scan.

Putting side effects in the accumulator. Keep it pure and put effects in tap or the subscriber.

Testing a reducer on its own

The biggest benefit of putting the state logic into a pure reducer function is that it can be tested without any streams. A test calls the reducer with a state and an action and compares the result with an expected state, which runs in microseconds and needs no scheduler. The stream layer then needs only a small test showing that actions flow through scan and out. Teams that mix the two end up with slow, hard-to-read tests that assert on timing when they mean to assert on logic.

Performance of immutable updates

Creating a new object for every action sounds expensive, and for small states it is not. Spreading an object with a dozen fields is cheap, and the garbage collector handles short-lived objects well. The cost appears with large collections: copying an array of ten thousand items for each action does real work. In that case, use a persistent data structure, a library that applies structural sharing, or keep the large collection outside the state and store only identifiers inside it. Measure first. Many apps never hit the limit.

Error handling inside scan

If the accumulator throws, the stream errors and the state is lost. A reducer should therefore never throw for bad input. Treat an unknown action as a no-op and a malformed payload as an error state or an ignored message. If you need to guard against a bug in the reducer, wrap the body in try and catch, log, and return the previous state, so one bad action does not take the whole store down.

Combining several sources of change

When state is changed by more than one stream, merge them into one stream of actions first, mapping each source to an action object, and run a single scan over the merged stream. Having two separate scan operators writing to overlapping state invites races. A single reducer is the one place where state changes, which makes the order of changes, and therefore the bugs, easy to follow.

Choosing between scan and a store library

For a counter, a form or a small widget, scan over a stream of actions is all the state management you need, and it adds no dependency. As the number of actions grows, as several parts of the application need the same state, or as you want devtools that replay and inspect actions, a store library offers structure that you would otherwise rebuild. The decision is not about which one is better, it is about the size of the state: the model is the same in both, a reducer folded over a stream of actions, and moving from one to the other later is a small step if the reducer is already a pure function.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.