Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Observable store with subscribe in JavaScript

106 An observable store, and the listener that leaves mid-notification

hard

Build a store: it holds state, subscribe(fn) returns an unsubscribe, and setting state notifies every listener with the new and previous state. Then handle the case that breaks naive implementations — a listener that unsubscribes another listener while the notification is still running — and prove the removed one was never called. Also prove that a listener added during a notification does not receive that notification, that setting an unchanged value notifies nobody, and that one listener throwing does not silence the rest.

Stuck? Three hints, smallest first
  1. 1. Copy the listener list before you walk it, or you are iterating a collection somebody is editing.
  2. 2. A copy is only half the fix: a listener removed after the copy was taken is still in your copy, so check it is still registered before calling it.
  3. 3. Give each unsubscribe a private flag so calling it twice is a no-op rather than a second delete that reports success.

The answer

function createStore(initial) {
  let state = initial;
  const listeners = new Set();
  const failures = [];

  return {
    get state() { return state; },
    get listenerCount() { return listeners.size; },
    get failures() { return failures.slice(); },

    subscribe(fn) {
      listeners.add(fn);
      let live = true;
      return function unsubscribe() {
        if (!live) return false;          // idempotent: a second call does nothing
        live = false;
        listeners.delete(fn);
        return true;
      };
    },

    set(patch) {
      const next = { ...state, ...patch };
      const changed = Object.keys(next).some((key) => next[key] !== state[key]);
      if (!changed) return 0;

      const previous = state;
      state = next;

      let delivered = 0;
      for (const fn of [...listeners]) {        // a snapshot, not the live Set
        if (!listeners.has(fn)) continue;       // left after the snapshot was taken
        delivered++;
        try {
          fn(state, previous);
        } catch (err) {
          failures.push(err.message);
        }
      }
      return delivered;
    },
  };
}

const store = createStore({ till: 'Balogun 1', naira: 0 });

const seen = [];
const off = store.subscribe((now, before) => seen.push(before.naira + ' -> ' + now.naira));
const firstDelivery = store.set({ naira: 4500 });
const afterOneEvent = [seen.slice(), store.state.naira];

off();
store.set({ naira: 9000 });
const ignoredAfterUnsubscribe = seen.length;
const secondOffReturns = off();
const stillEmpty = store.listenerCount;

// A warden that removes the victim, subscribed FIRST so it runs first.
const victimCalls = [];
const wardenCalls = [];
const staged = createStore({ open: false });
let removeVictim;
staged.subscribe(() => { wardenCalls.push('warden ran'); removeVictim(); });
removeVictim = staged.subscribe(() => { victimCalls.push('victim ran'); });
const deliveredWhileRemoving = staged.set({ open: true });
const victimNeverRan = [wardenCalls.length, victimCalls.length, staged.listenerCount];

// A listener that subscribes another one while the notification is in flight.
const lateCalls = [];
const growing = createStore({ n: 0 });
let added = false;
growing.subscribe(() => {
  if (added) return;
  added = true;
  growing.subscribe(() => lateCalls.push('late ran'));
});
const deliveredWhileAdding = growing.set({ n: 1 });
const lateMissedThisRound = lateCalls.length;
const lateGetsTheNextOne = [growing.set({ n: 2 }), lateCalls.length];

const noopSet = store.set({ till: 'Balogun 1' });

const order = [];
const guarded = createStore({ n: 0 });
guarded.subscribe(() => { order.push('first'); throw new Error('listener blew up'); });
guarded.subscribe(() => order.push('second'));
const deliveredDespiteThrow = guarded.set({ n: 1 });

// The naive version, for contrast: it walks the live Set.
function naiveStore() {
  const listeners = new Set();
  return {
    subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); },
    notify() {
      let delivered = 0;
      for (const fn of listeners) { delivered++; fn(); if (delivered > 50) break; }
      return delivered;
    },
  };
}
const naive = naiveStore();
let grewOnce = false;
naive.subscribe(() => {
  if (grewOnce) return;
  grewOnce = true;
  naive.subscribe(() => {});
});
const naiveDelivered = naive.notify();

console.log('after one event  :', afterOneEvent);
console.log('warden/victim    :', victimNeverRan, 'delivered', deliveredWhileRemoving);
console.log('late subscriber  :', lateMissedThisRound, 'then', lateGetsTheNextOne[1]);
console.log('failures kept    :', guarded.failures);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('a subscriber is handed the new state and the previous one', afterOneEvent, [['0 -> 4500'], 4500]);
test('unsubscribing really stops delivery, and a second call is a no-op', [ignoredAfterUnsubscribe, secondOffReturns, stillEmpty], [1, false, 0]);
test('a listener removed mid-notification is never called', victimNeverRan, [1, 0, 1]);
test('so only the listeners still registered when their turn came are counted', deliveredWhileRemoving, 1);
test('a listener added mid-notification misses that round', [deliveredWhileAdding, lateMissedThisRound], [1, 0]);
test('and receives the next one', lateGetsTheNextOne, [2, 1]);
test('setting a value to what it already was notifies nobody', [noopSet, store.state.till], [0, 'Balogun 1']);
test('one listener throwing does not stop the next, and the error is kept', [deliveredDespiteThrow, order, guarded.failures], [2, ['first', 'second'], ['listener blew up']]);
test('walking the live Set instead would deliver to the listener just added', naiveDelivered, 2);

The whole exercise is in one line: for (const fn of [...listeners]). Iterating the live Set means a listener can edit the collection you are walking, and the last assertion shows what that costs — the listener added mid-notification is visited by the same pass, because a Set iterator does see entries appended during iteration. In a real app that is how one subscribe inside a listener turns into an unbounded loop.

The copy alone is not enough, and that is the trap worth remembering. Once you snapshot, your list is stale in the other direction: a listener that unsubscribed a moment ago is still in your copy, so you would call somebody who has already torn down their component and be reading freed state. The listeners.has(fn) re-check inside the loop is what makes the third assertion true. Two lines, opposite failure modes, and both are needed.

The rest is the small print that separates a working store from a demo. unsubscribe is idempotent, so a component unmounting twice does not report a removal it did not perform. An unchanged value notifies nobody, which is what stops a render loop. And listener errors are collected rather than allowed to propagate, because a notification that aborts halfway leaves half your app updated with no way to tell which half.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.