Skip to content

Connectivity Monitor

This example monitors the health of a network connection with a three-state FSM. It simulates health checks client-side, without a backend, and drives a real-time UI entirely through FSM event subscriptions. The browser’s online/offline events feed the FSM as inputs, and everything downstream is reactive.

  • Async operations in _onEnter: The checking state starts an async health check and feeds the result back as an FSM input via fsm.handle(). The FSM stays synchronous, and the async work happens in the side effect.
  • AbortController cleanup in _onExit: Each in-flight health check gets an AbortController. When the FSM leaves checking, _onExit calls abort() so stale callbacks cannot trigger unexpected transitions.
  • Timer management co-located in _onEnter/_onExit: The retry timer (offline) and heartbeat timer (online) are both started in _onEnter and cleared in _onExit. Cleanup is guaranteed regardless of which input caused the transition.
  • Custom events emitted from handlers: checking._onEnter emits checkCountUpdated so the UI can display progress without polling state. offline._onEnter emits maxChecksReached when the retry cap is hit.
  • Event-driven UI: main.ts subscribes to transitioned and custom events. The UI reads currentState() once for the initial render and reacts to events after that.
              connectionLost
  online ─────────────────────> checking
    ^                              |   |
    |       healthCheckPassed      |   |
    +──────────────────────────────+   |
                                       | healthCheckFailed
              connectionRestored       v
  offline <─────────────────────── checking
    |   ^
    |   | retryCheck (timer, up to MAX_CHECKS)
    +───+
From Input To
online connectionLost checking
offline connectionRestored checking
offline retryCheck checking
checking healthCheckPassed online
checking healthCheckFailed offline
checking connectionLost offline

The online state also runs a periodic heartbeat. If it fails, it fires connectionLost, the same input the browser offline event sends, and the FSM does not distinguish the source.

The checking state is the core of the example: _onEnter starts async work and feeds the result back as an FSM input. _onExit aborts any in-flight request so stale callbacks can’t fire after the FSM leaves the state.

checking: {
    _onEnter({ ctx, emit }) {
        ctx.checkCount++;
        emit("checkCountUpdated", { checkCount: ctx.checkCount });

        // AbortController lets _onExit cancel an in-flight check
        // if the FSM leaves this state before the promise settles.
        ctx.checkController = new AbortController();

        checkHealth(ctx.checkController.signal)
            .then(res => {
                fsm.handle(res.ok ? "healthCheckPassed" : "healthCheckFailed");
            })
            .catch(() => {
                // Aborted checks reject here. healthCheckFailed is harmless
                // from any state other than `checking` — emits `nohandler`, no transition.
                fsm.handle("healthCheckFailed");
            });
    },

    _onExit({ ctx }) {
        // Abort any in-flight check so stale callbacks don't call fsm.handle()
        // after we've already left this state.
        if (ctx.checkController !== null) {
            ctx.checkController.abort();
            ctx.checkController = null;
        }
    },

    healthCheckPassed: "online",
    healthCheckFailed: "offline",
    connectionLost: "offline",
},

fsm is declared before createFsm() so _onEnter callbacks can close over it. _onEnter itself runs synchronously during createFsm(), and the closure is safe because only the promise continuations created inside _onEnter read fsm. Those continuations run after createFsm() returns and fsm is assigned.

examples/connectivity/