Skip to content

Instantly share code, notes, and snippets.

@azamsharp
Created June 16, 2021 03:42
Show Gist options
  • Save azamsharp/50e8815795499cb06a060aa61a1da490 to your computer and use it in GitHub Desktop.
Save azamsharp/50e8815795499cb06a060aa61a1da490 to your computer and use it in GitHub Desktop.
import UIKit
// Dispatch Groups
func collectAllReviewIds() {
let group = DispatchGroup()
var reviewIds: [Int] = []
group.enter()
getReviewIdsFromGoogle { ids in
reviewIds.append(contentsOf: ids)
group.leave()
}
group.enter()
getReviewIdsFromYelp { ids in
reviewIds.append(contentsOf: ids)
group.leave()
}
group.enter()
getReviewIdsFromNextDoor { ids in
reviewIds.append(contentsOf: ids)
group.leave()
}
// example of a function where the function is responsible for calling
// the enter and leave events
getReviewsFromAmazon(group: group) { ids in
reviewIds.append(contentsOf: ids)
}
group.notify(queue: DispatchQueue.global()) {
// handle reviewIds
print(reviewIds)
}
}
func getReviewsFromAmazon(group: DispatchGroup, completion: @escaping ([Int]) -> Void) {
group.enter()
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
let result = Array(repeating: 0, count: 5).map { _ in
return Int.random(in: 1...20)
}
completion(result)
group.leave()
}
}
func getReviewIdsFromGoogle(completion: @escaping ([Int]) -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
let result = Array(repeating: 0, count: 5).map { _ in
return Int.random(in: 1...20)
}
completion(result)
}
}
func getReviewIdsFromYelp(completion: @escaping ([Int]) -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
let result = Array(repeating: 0, count: 5).map { _ in
return Int.random(in: 1...20)
}
completion(result)
}
}
func getReviewIdsFromNextDoor(completion: @escaping ([Int]) -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
let result = Array(repeating: 0, count: 5).map { _ in
return Int.random(in: 1...20)
}
completion(result)
}
}
collectAllReviewIds()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment