Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A small wrapper that manages multiple DispatchWorkItems
import Foundation
class Dispatcher {
private var items = [DispatcherIdentifier: DispatchWorkItem]()
private let queue: DispatchQueue
deinit {
cancelAllActions()
}
init(_ queue: DispatchQueue = .main) {
self.queue = queue
}
func schedule(after timeInterval: TimeInterval,
with identifier: DispatcherIdentifier,
on queue: DispatchQueue? = nil,
action: @escaping () -> Void) {
cancelAction(with: identifier)
print("Scheduled \(identifier)")
let item = DispatchWorkItem(block: action)
items[identifier] = item
(queue ?? self.queue).asyncAfter(deadline: .now() + timeInterval, execute: item)
}
@discardableResult
func cancelAction(with identifier: DispatcherIdentifier) -> Bool {
guard let item = items[identifier] else {
return false
}
defer {
items[identifier] = nil
}
guard !item.isCancelled else {
return false
}
item.cancel()
print("Cancelled \(identifier)")
return true
}
func cancelAllActions() {
items.keys.forEach {
items[$0]?.cancel()
items[$0] = nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.