Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/kiishi/statemachine
Simple library for implementing state machines
https://github.com/kiishi/statemachine
state state-machine
Last synced: about 2 months ago
JSON representation
Simple library for implementing state machines
- Host: GitHub
- URL: https://github.com/kiishi/statemachine
- Owner: kiishi
- Created: 2019-09-23T02:37:39.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2021-07-23T20:13:57.000Z (over 3 years ago)
- Last Synced: 2024-08-04T01:19:59.098Z (5 months ago)
- Topics: state, state-machine
- Language: Go
- Homepage:
- Size: 22.5 KB
- Stars: 12
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
- awesome-list - statemachine
README
## State Machine ![](https://github.com/kiishi/statemachine/workflows/CI/badge.svg)
Cool-ish state machineπ πΎ### Simple Usage
```go
package mainimport (
"fmt"
machine "github.com/kiishi/statemachine"
)type FoodState struct {
name string
}func (m *FoodState) GetIdentifier() string {
return m.name // name must be unique
}func main() {
raw := FoodState{"raw"}
cooked := FoodState{"cooked"}
statemachine := machine.NewMachine()
statemachine.AddState(&raw) // this becomes the initial state
statemachine.AddState(&cooked)
statemachine.AddTransition(&machine.TransitionRule{
EventName: "move",
CurrentState: &raw,
DestinationState: &cooked,
})
err := statemachine.Emit("move")
if err != nil {
// handle error here
panic(err)
}// validate
fmt.Println(statemachine.GetCurrentState().GetIdentifier()) // outputs "cooked"}
```### Not So Simple Usage
```go
package mainimport (
"fmt"
machine "github.com/kiishi/statemachine"
)type FoodState struct {
name string
}func (m *FoodState) GetIdentifier() string {
return m.name // name must be unique
}func main() {
raw := FoodState{"raw"}
cooked := FoodState{"cooked"}statemachine := machine.NewMachine(
&machine.Config{
States: []machine.State{
&raw, // first state is initial
&cooked,
},
Transitions: []*machine.TransitionRule{
&machine.TransitionRule{
EventName: "cook",
CurrentState: &raw,
DestinationState: &cooked,
OnTransition: func(
rule *machine.TransitionRule,
newState,
previousState machine.State,
) {
fmt.Println("Food is ready")
},
},
},
})// run a transition
err := statemachine.Emit("cook")
if err != nil {
// handle error here
panic(err)
}// validate
fmt.Println(statemachine.GetCurrentState().GetIdentifier()) // outputs "cooked"
}
```