Skip to content

Instantly share code, notes, and snippets.

@foresta
Last active September 9, 2019 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foresta/cfc4440f74ae817339ef250519a2a37e to your computer and use it in GitHub Desktop.
Save foresta/cfc4440f74ae817339ef250519a2a37e to your computer and use it in GitHub Desktop.
Async Request Sample
typealias AsyncCallback = () -> Void
func getFriends() {
let dispatchGroup = DispatchGroup()
let dispatchQueue = DispatchQueue(label: "twitterAPIQueue", attributes: .concurrent)
// 非同期のGroupとQueueに書くメソッドを割り当てる
dispatch(group: dispatchGroup, queue: dispatchQueue, method: getFollows)
dispatch(group: dispatchGroup, queue: dispatchQueue, method: getFollowers)
dispatchGroup.notify(queue: .main) {
print("All Process Done!")
// TODO: 突合する処理とかを書く
}
}
private func dispatch(group: DispatchGroup, queue: DispatchQueue, method: @escaping (@escaping AsyncCallback) -> Void) {
// ここで非同期のグループに入る
group.enter()
queue.async(group: group) {
// 非同期で引数で与えられたメソッドを実行
method {
// そのコールバックでgroupから抜ける
group.leave()
}
}
}
/
private func getFollows(completion: @escaping AsyncCallback) {
fetchFollowsAsync() {
// Store follows
completion()
}
}
private func getFollowers(completion: @escaping AsyncCallback) {
fetchFollowersAsync() {
// Store
completion()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment