state4d 0.0.1
state4d: ^0.0.1 copied to clipboard
Simple state management for Dart
State4d #
A simple state machine library for Dart, ported from state4k.
Installation #
dependencies:
state4d: ^1.0.0
Concepts #
To model a state machine, you need:
- Entity - The object being modeled, which holds the current state
- States - The discrete states the entity can be in
- Events - Triggers that cause transitions between states
- Commands (optional) - Actions that execute when entering a state, which may generate events
Transitions occur in one of two ways:
- Receive a known out-of-band Event and transition to a new state
- Receive and process a Command, which will result in one of a discrete set of Events
The storage of the controlled entity is done entirely outside of State4d - the library is purely functional and returns new entity instances.
Example: Making Tea #
import 'package:result4d/result4d.dart';
import 'package:state4d/state4d.dart';
// The entity - tracks the state
class CupOfTea {
final TeaState state;
final String lastAction;
CupOfTea(this.state, this.lastAction);
CupOfTea copyWith({TeaState? state, String? lastAction}) =>
CupOfTea(state ?? this.state, lastAction ?? this.lastAction);
}
// The states
enum TeaState { getCup, boilingWater, steepingTea, checkForMilk, whiteTea, blackTea }
// Commands that can be triggered on state entry
enum TeaCommands { doYouHaveMilk }
// Events that trigger transitions
sealed class TeaEvent {}
class TurnOnKettle extends TeaEvent {}
class PourWater extends TeaEvent {}
class MilkPlease extends TeaEvent {}
class NoMilkPlease extends TeaEvent {}
class MilkIsFull extends TeaEvent {}
class MilkIsEmpty extends TeaEvent {}
// Lens to get/set state on the entity
final lens = StateIdLens<CupOfTea, TeaState>(
(entity) => entity.state,
(entity, state) => entity.copyWith(state: state),
);
// Command handler
Result<void, String> commands(CupOfTea entity, TeaCommands command) {
print('Issuing command $command');
return Success(null);
}
// Define the state machine
final teaStateMachine = StateMachine.create(commands, lens).states<TeaEvent>(
(state) => [
state(TeaState.getCup)
.transition(TurnOnKettle, TeaState.boilingWater),
state(TeaState.boilingWater)
.transition(PourWater, TeaState.steepingTea,
(event, entity) => entity.copyWith(lastAction: 'Waiting...')),
state(TeaState.steepingTea)
.onEnter(TeaCommands.doYouHaveMilk)
.transition(MilkPlease, TeaState.checkForMilk)
.transition(NoMilkPlease, TeaState.blackTea),
state(TeaState.checkForMilk)
.transition(MilkIsFull, TeaState.whiteTea)
.transition(MilkIsEmpty, TeaState.blackTea),
state(TeaState.blackTea),
],
);
Usage #
Event-based transitions #
final result = await teaStateMachine.transition(
CupOfTea(TeaState.getCup, '-'),
TurnOnKettle(),
);
switch (result) {
case Success(value: OK(entity: final tea)):
print('New state: ${tea.state}');
case Success(value: IllegalEvent()):
print('Event not valid for current state');
case Failure(reason: final error):
print('Error: $error');
}
Command-based transitions #
Commands are useful when the resulting event depends on external factors:
final result = await teaStateMachine.transitionCommand(
cupOfTea,
TeaCommands.doYouHaveMilk,
(entity) async {
// Check fridge, call API, etc.
final hasMilk = await checkFridge();
return hasMilk ? Success(MilkIsFull()) : Success(MilkIsEmpty());
},
);
Queued transitions with Runner #
For sequential transitions that should execute in order:
final runner = teaStateMachine.run(CupOfTea(TeaState.getCup, '-'));
runner.transition(TurnOnKettle());
runner.transition(PourWater());
final result = await runner.transition(MilkPlease());
// result contains the entity after all three transitions
Each call returns a Future - await any call to get the result up to that point:
final runner = teaStateMachine.run(initialEntity);
var result = await runner.transition(TurnOnKettle());
expect(result.value.state, TeaState.boilingWater);
result = await runner.transition(PourWater());
expect(result.value.state, TeaState.steepingTea);
Visualization #
Render the state machine using pluggable renderers. Mermaid and PlantUML are included:
print(teaStateMachine.renderUsing(renderMermaid));
print(teaStateMachine.renderUsing(renderPuml));
Output (Mermaid):
stateDiagram-v2
getCup
boilingWater
steepingTea
checkForMilk
blackTea
getCup --> boilingWater : TurnOnKettle
boilingWater --> steepingTea : PourWater
steepingTea --> checkForMilk : MilkPlease
steepingTea --> blackTea : NoMilkPlease
checkForMilk --> whiteTea : MilkIsFull
checkForMilk --> blackTea : MilkIsEmpty
Write your own renderer by implementing String Function(List<State>).
License #
This project is licensed under the Apache 2.0 License - see the LICENSE file for details.
Acknowledgments #
- Original state4k Kotlin library by the fork-handles team