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 .
The machine definition is a simple object that:
- lists all possible states (as its top-level properties), and
- 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.
StateMachine.init returns MachineState , capturing the definition of the machine and its current state:
To attempt to change state, use StateMachine.to
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 :
Module Flow.StateMachine