SideEffects

FSM2 allows you to trigger individual side effects for each transition that occurs.

The side effect is a lambda which will be called when the transition is triggered.

Side effects make it easy to carry out a task when a transition occurs. For example if the Event is 'OnApplyHeat' you could use a side effect to recalculate the temperature of a the water as the result of being heated.

A transition that fails to pass its guard condition will not be triggered and its side effect will not be called.

The sideEffect is called AFTER the original states onExit method is called but before the new states onEnter method is called.

When the sideEffect is called the State Machine is still considered to be in the original state.

It is safe to call stateMachine.applyEvent call whilst in sideEffect. The event will be queued and processed once the current transition has been completed.

void main() {
  final machine = StateMachine.create((g) => g
    ..initialState(Solid())
    ..state<Solid>((b) => b
      ..on<OnHeat, Liquid>(sideEffect: (e) => print('I melted')))
 ));

In this example the side effect is only called when the onHeat event is sent when the FSM is in the Solid state.

machine.applyEvent(OnHeat());
> I melted

The side effect will be called every time the transition occurs.

Nested and Concurrent Regions

A single transition may result in multiple state changes when Nested or Concurrent Regions are used.

In these cases the sideEffect is still only called once

Last updated