Skip to content

thatfactory/cgkstatemachine

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

13 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

swift-version xcode-version spm-ready platforms license release

CGKStateMachine πŸ”€

A custom GKStateMachine subclass that allows GKState changes to be observed using Combine.

Usage Examples

// Create a state machines of `CGKStateMachine` type.
let cgkStateMachine = CGKStateMachine(
    states: [
        FirstState(),
        SecondState()
    ]
)

// Create states of `CGKState` type.
class FirstState: CGKState {}
class SecondState: CGKState {}

// Sink `publishedState`.
var cancellables = Set<AnyCancellable>()

cgkStateMachine.publishedState
    .sink { state in
        // React here πŸ‘ˆπŸ»πŸ‘ˆπŸ»πŸ‘ˆπŸ»
    }
    .store(in: &cancellables)

// Enter states and get notified.
cgkStateMachine.enter(FirstState.self)
cgkStateMachine.enter(SecondState.self)

Notice

Apple implemented a publisher(for:) on NSObject.
This publisher allows for subscribing to KVO changes on classes that inherit from NSObject.

GKStateMachine inherits from NSObject.
So in theory one could try using:

gkStateMachine.publisher(for: \.currentState).sink { state in
    ...
}

... however it doesn't seem that GKStateMachine is KVO-compliant.
In my experience, with the above approach only the first state gets published.

That's why CGKStateMachine was created.

Integration

Xcode

Use Xcode's built-in support for SPM.

or...

Package.swift

In your Package.swift, add CGKStateMachine as a dependency:

dependencies: [
    .package(
        url: "https://github.com/thatfactory/cgkstatemachine",
        from: "0.1.0"
    )
]

Associate the dependency with your target:

targets: [
    .target(
        name: "YourTarget",
        dependencies: [
            .product(
                name: "CGKStateMachine",
                package: "cgkstatemachine"
            )
        ]
    )
]

Run: swift build

About

A custom GKStateMachine subclass that allows GKState changes to be observed via Combine πŸ”€

Topics

Resources

Stars

Watchers

Forks

Languages