Last active
August 28, 2019 07:03
-
-
Save Qata/72b7add946945351f0d635be0f4d8d4a to your computer and use it in GitHub Desktop.
Actors using Combine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Combine | |
import Foundation | |
class Actor<Message, State> { | |
@Published public private(set) var state: State | |
private var cancellables: Set<AnyCancellable> | |
let inbox = PassthroughSubject<Message, Never>() | |
init(initialState: State) { | |
state = initialState | |
cancellables = [] | |
inbox.sink { [unowned self] message in | |
self.state = self.update(message: message, state: self.state) | |
}.store(in: &cancellables) | |
} | |
func update(message: Message, state: State) -> State { | |
return state | |
} | |
} | |
enum Actors { | |
class Counter: Actor<(), Int> { | |
override func update(message: (), state: Int) -> Int { | |
return state + 1 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment