Skip to content

Instantly share code, notes, and snippets.

@kien-hoang
Last active January 31, 2023 02:29
Show Gist options
  • Save kien-hoang/c0e456f70f083d39ffc77f87ade6a9bd to your computer and use it in GitHub Desktop.
Save kien-hoang/c0e456f70f083d39ffc77f87ade6a9bd to your computer and use it in GitHub Desktop.
How to know when multiple asynchronous works are done?
/*
DispatchGroup
Create a group, register a bunch of `enter` events, `leave` when a task completes
and the group will automatically do code in `notify` block when all work is done
*/
import UIKit
// Example for calling API
func callAPI(delay: Int, completion: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + DispatchTimeInterval.seconds(delay)) {
completion()
}
}
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
callAPI(delay: 2) { [weak dispatchGroup] in
defer { dispatchGroup?.leave() }
// handle API result here
print("Finish API 1")
}
dispatchGroup.enter()
callAPI(delay: 1) { [weak dispatchGroup] in
defer { dispatchGroup?.leave() }
print("Finish API 2")
}
dispatchGroup.enter()
callAPI(delay: 4) { [weak dispatchGroup] in
defer { dispatchGroup?.leave() }
print("Finish API 3")
}
dispatchGroup.notify(queue: .main) {
print("Finish 3 APIs")
}
/*
Finish API 2
Finish API 1
Finish API 3
Finish 3 APIs
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment