Skip to content

Instantly share code, notes, and snippets.

@davbeck
Created May 6, 2024 20:51
Show Gist options
  • Save davbeck/5dbe11bd5b68efa4e1768727b968882f to your computer and use it in GitHub Desktop.
Save davbeck/5dbe11bd5b68efa4e1768727b968882f to your computer and use it in GitHub Desktop.
import Foundation
import Combine
/// Calls all handlers when triggered, waiting for them to finish running.
actor HandlerManager<Input: Sendable> {
typealias Handler = @Sendable (Input) async -> Void
private var handlers: [UUID: Handler] = [:]
func register(_ handler: @escaping Handler) -> any Cancellable {
let id = UUID()
handlers[id] = handler
return AnyCancellable {
Task {
self.handlers[id] = nil
}
}
}
func send(_ input: Input) async {
for handler in handlers.values {
await handler(input)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment