A custom GKStateMachine
subclass that allows GKState changes to be observed using Combine.
// 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)
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.
Use Xcode's built-in support for SPM.
or...
In your Package.swift
, add CGKStateMachine
as a dependency:
dependencies: [
.package(url: "https://github.com/backslash-f/cgkstatemachine", from: "0.1.0")
],
Associate the dependency with your target:
targets: [
.target(name: "App", dependencies: ["CGKStateMachine"])
]
Run: swift build