Last active
August 17, 2019 14:17
-
-
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
This file contains hidden or 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
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