Last active
April 2, 2018 12:08
-
-
Save mdflores/c1338e5b8a6086b3402aea2e516e7432 to your computer and use it in GitHub Desktop.
RevokableTask adds a task delayed to the main queue which can be revoked or cancelled.
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
typealias TaskHandler = () -> () | |
class RevokableTask { | |
private(set) var isCancelled: Bool = false | |
private(set) var task: TaskHandler | |
private(set) var delayTime: DispatchTime | |
private(set) var identifier: String | |
init(delayInSeconds: Double, task: @escaping TaskHandler) { | |
self.task = task | |
self.delayTime = .now() + delayInSeconds | |
self.identifier = UUID().uuidString | |
} | |
func execute() { | |
DispatchQueue.main.asyncAfter(deadline: self.delayTime) { | |
if !self.isCancelled { | |
self.task() | |
} | |
} | |
} | |
func revoke() { | |
self.isCancelled = true | |
} | |
} |
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
let task = RevokableTask(delayInSeconds: 120) { | |
print("This task must not be executed...") | |
} | |
let task2 = RevokableTask(delayInSeconds: 120) { | |
print("Task is executing...") | |
} | |
task.execute() | |
task2.execute() | |
task.revoke() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment