This is a simple state machine with generic types for event and state identifiers. Possible state transitions as well as a start state must be given. Same state transitions can be allowed or forbidden depending upon configuration. A callback after a transition is available.
- Create state and event types, for example:
type (
ExampleState string
ExampleEvent string
)
- Define available state identifiers:
var (
exampleStateA1 ExampleState = "example-state-A1"
exampleStateA2 ExampleState = "example-state-A2"
exampleStateB ExampleState = "example-state-B"
exampleStateC ExampleState = "example-state-C"
)
- Define available event identifiers:
var (
exampleEventA ExampleEvent = "example-event-A"
exampleEventB ExampleEvent = "example-event-B"
)
- Define available events:
var events = []Event[ExampleState, ExampleEvent] {
{
Event: exampleEventA,
Sources: []ExampleState {
exampleStateA1,
exampleStateA2,
},
Destination: exampleStateB,
},
{
Event: exampleEventB,
Sources: []ExampleState {
exampleStateB,
},
Destination: exampleStateC,
},
}
- Create settings:
var settings = Settings{
AllowSameStateTransition: false,
}
- Define callback function:
var callback = func(transition Transition[ExampleState, ExampleEvent]) {
...
}
- Create state machine:
var machine = NewMachine(exampleStateA1, events, settings, callback)
- Start triggering events:
err := machine.Trigger(exampleEventA); if err != nil {
...
}