Skip to content

Basic usage

A simple way of using the state machine is the functional, immutable approach. Create the machine with its definition and initial state with StateMachine.init .

const machine = StateMachine.init({
on: "off",
off: "on"
}, "on");

The machine definition is a simple object that:

  1. lists all possible states (as its top-level properties), and
  2. for each state, what other state(s) can be transitioned to, or null if it is a final state.

The following example has four possible states (‘wakeup’, ‘sleep’, ‘coffee’, ‘breakfast’, ‘bike’). ‘sleep’ can only transition to the ‘wakeup’ state, while ‘wakeup’ can transition to either ‘coffee’ or ‘breakfast’.

Use null to signify the final state. Multiple states can terminate the machine if desired.

import { StateMachine } from "https://unpkg.com/ixfx/dist/flow.js"
const definition = {
sleep: `wakeup`,
wakeup: [`coffee`, `breakfast`],
coffee: `bike`,
breakfast: `bike`,
bike: null
}
let sm = StateMachine.init(definition, `sleep`);

StateMachine.init returns MachineState , capturing the definition of the machine and its current state:

// Current state
sm.value; // eg. 'bike'
// List of unique states visited
sm.visited; // eg. ['sleep', 'wakeup']
// Original machine definition
sm.machine;

To attempt to change state, use StateMachine.to

// Transition existing machine to state 'wakeup'
sm = StateMachine.to(sm, 'wakeup');
sm.value; // 'wakeup'

If this is a legal transition, you’ll get a new MachineState object. If not, an exception will be thrown. Note that the state is immutable - a transition results in a new object.

Here are some more helper functions :

// String array of possible next states
StateMachine.possible(sm);
// Returns _true_ if state machine cannot transition further
StateMachine.isDone(sm);
// Try to automatically move to next state
sm = StateMachine.next(sm);
Module Flow.StateMachine