Skip to content

statemachine is a Golang implementation for a simple state machine. You can dispatch events and handle according to your logic plus a tiny but nice to have mermaid printable feature

Notifications You must be signed in to change notification settings

blue-factory/statemachine

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

statemachine

--

Statemachine is a simple state machine implementation in go. We can set up a few events and its handlers in order to manage correctly the satate and dispatche the new state according to the flow definition.

Simple usage

func main() {
	sm := statemachine.New(
		&statemachine.Event{Name: eventFetch},
		map[string]statemachine.State{
			eventFetch: {
				EventHandler: handleFetchInfoFn,
				Destination:  []string{eventFetch, eventCalculateVolume},
			},
			eventCalculateVolume: {
				EventHandler: handleCalculateVolumeFn,
				Destination:  []string{eventFetch, eventBuySecondaryMarket},
			},
			eventBuySecondaryMarket: {
				EventHandler: ism.HandleBuySecondaryMarket,
				Destination:  []string{eventFetch, eventBuySecondaryMarket, eventCheckOrderExecuted},
			},
			eventCheckOrderExecuted: {
				EventHandler: handleCheckOrderExecutedFn,
				Destination:  []string{eventFinish, eventCheckOrderExecuted, eventCancelOrder},
			},
			eventCancelOrder: {
				EventHandler: handleCancelOrderFn,
				Destination:  []string{eventFinish, eventCancelOrder},
			},
			eventFinish: {
				EventHandler: handleFinishFn,
				Destination:  []string{statemachine.EventAbort},
			},
		},
		logger,
	)
}

func handleFinishFn(e *statemachine.Event) (*statemachine.Event, error) {
	return &statemachine.Event{Name: statemachine.EventAbort}, nil
}

You can also print a mermaid diagram based on your statemachine implementation and this is an example of the result

Screen Shot 2021-04-24 at 6 45 01 PM

For more use cases see the folder examples.

About

statemachine is a Golang implementation for a simple state machine. You can dispatch events and handle according to your logic plus a tiny but nice to have mermaid printable feature

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages