Swiftpack.co - carson-katri/state-machine as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by carson-katri.
carson-katri/state-machine v1.1.0
Dead simple state machines in Swift
⭐️ 12
πŸ•“ 3 years ago
.package(url: "https://github.com/carson-katri/state-machine.git", from: "v1.1.0")

State Machine

Dead simple state machines in Swift.

Usage

Setup your states:

enum FetchStates: StateList {
    case idle, fetching, error
}

and your actions:

enum FetchActions: ActionList {
    case fetch, success, failure, retry, reset
}

Then create your machine:

var machine: StateMachine<FetchStates, FetchActions> = .idle <> .fetching <> .error <|> .idle

Bind your actions:

try machine.bindAction(.fetch, to: .idle)
try machine.bindAction(.success, to: .fetching, .cycle) // Go back to beginning of cycle (first <> before current state)
try machine.bindAction(.failure, to: .fetching)
try machine.bindAction(.retry, to: .error, .cycle)  // Go back to beginning of cycle (first <> before current state)
try machine.bindAction(.reset, to: .error)

Add events for your states and/or actions:

machine.addEvent(on: [.fetch, .retry]) {
    // Perform fetch operation
}
machine.addEvent(on: .success) {
    // Show data
}
machine.addEvent(on: .error) {
    // Show error
}

Send events:

try machine.send(.fetch)

And that's all it takes to get a working state machine πŸŽ‰

This state machine is equivalent to:

β”Œβ”€β”€β”€β”€β” ----fetch---> β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” --failure-> β”Œβ”€β”€β”€β”€β”€β”
β”‚idleβ”‚               β”‚fetchingβ”‚             β”‚errorβ”‚
β””β”€β”€β”€β”€β”˜ <--success--- β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜ <--retry--- β””β”€β”€β”€β”€β”€β”˜
  ⬑-------------------reset--------------------β”˜

Operators

  • |> One way state direction.

    Always goes to the next state

  • <> Two way state direction.

    Can either go to the next state, or go back to the first link in cycle (.first <> .second <> .third, cycle from .second or .third would go to .first)

  • <|> Loop state direction.

    Returns to the initial state

GitHub

link
Stars: 12
Last commit: 3 years ago
Advertisement: IndiePitcher.com - Cold Email Software for Startups

Release Notes

v1.1.0
3 years ago

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics