Last active
September 9, 2019 04:56
-
-
Save foresta/cfc4440f74ae817339ef250519a2a37e to your computer and use it in GitHub Desktop.
Async Request Sample
This file contains 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
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