Skip to content

Instantly share code, notes, and snippets.

@prat14k
Created July 2, 2019 11:15
Show Gist options
  • Save prat14k/09dbe314ae9a8e3f6cc396bd98076aa8 to your computer and use it in GitHub Desktop.
Save prat14k/09dbe314ae9a8e3f6cc396bd98076aa8 to your computer and use it in GitHub Desktop.
DispatchGroup Demo
/*
##: DispatchGroup
- Lets you wait for task to happen and then we can continue to do what we want
- Whenever starting a task, use enter() to denote the start of a task
- Whenever completed, use leave() to denote finishing of the task
- You call wait() to block the current thread while waiting for tasks’ completion.
This waits forever which is fine because the photos creation task always completes.
You can use wait(timeout:) to specify a timeout and bail out on waiting after a specified time.
- To let know when all tasks are done, use notify() which automatically gets triggered when all tasks are done
*/
import UIKit
var items = [Int]()
func getItems() -> [Int] {
let numberOfItems = arc4random_uniform(10) + 1
return (0..<numberOfItems).map { _ in Int(arc4random_uniform(100)) }
}
func run(after delay: Int, tasks: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(delay)) {
tasks()
}
}
let dispatchGroup = DispatchGroup()
let tasks = {
items.append(contentsOf: getItems())
print(items)
dispatchGroup.leave()
}
dispatchGroup.enter()
run(after: 2) { tasks() }
dispatchGroup.enter()
run(after: 4) { tasks() }
dispatchGroup.enter()
run(after: 6) { tasks() }
dispatchGroup.notify(queue: .main) {
print("\n## Done")
print(items)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment