Skip to content

Instantly share code, notes, and snippets.

@standinga
Last active August 17, 2019 14:17
Show Gist options
  • Save standinga/2d916ff149c2fb1df7fb21a16854f3a5 to your computer and use it in GitHub Desktop.
Save standinga/2d916ff149c2fb1df7fb21a16854f3a5 to your computer and use it in GitHub Desktop.
fetchData function for medium blog post about DispatchGroup and DispatchSemaphore, https://link.medium.com/zJMQPUHaeZ
func combineAsyncCallsWithSemaphore(completionHandler: @escaping (String)->()) {
let semaphore = DispatchSemaphore(value: 0)
var text = ""
DispatchQueue.global().async {
fetchData(0, delay: 0.4) {
text += $0
semaphore.signal()
}
semaphore.wait() // wait for the first fetchData complete
fetchData(1, delay: 0.2) {
text += $0
semaphore.signal()
}
semaphore.wait() // wait for the second fetchData complete
completionHandler(text)
}
}
combineAsyncCallsWithSemaphore() {
print($0)
exit(0)
}
RunLoop.current.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment