Created
February 12, 2019 13:22
-
-
Save natanrolnik/1a5d07ea79ba529eafb9b03d21111705 to your computer and use it in GitHub Desktop.
A small wrapper that manages multiple DispatchWorkItems
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 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