Skip to content

Instantly share code, notes, and snippets.

@cozzin
Last active March 16, 2018 05:43
Show Gist options
  • Save cozzin/0ee05e5d759cc80e962ffb315341e8e9 to your computer and use it in GitHub Desktop.
Save cozzin/0ee05e5d759cc80e962ffb315341e8e9 to your computer and use it in GitHub Desktop.
async with completion
extension DispatchQueue {
public func async(execute work: @escaping () -> Void, complete: @escaping () -> Void) {
async(execute: [work], complete: complete)
}
public func async(execute works: [() -> Void], complete: @escaping () -> Void) {
let dispatchGroup = DispatchGroup()
works.forEach { work in
async(group: dispatchGroup) {
work()
}
}
dispatchGroup.notify(queue: .main) {
complete()
}
}
}
// main 에서 작업 후, main에서 completion
DispatchQueue.main.async(execute: {
print("main single task")
}, complete: {
print("main single task done")
})
// background 에서 작업 후, main에서 completion
DispatchQueue.global(qos: .background).async(execute: {
print("background single task")
}, complete: {
print("background single task done")
})
// main 에서 모든 작업 실행 후, main에서 completion
DispatchQueue.main.async(execute:
[
{
print("main task 1")
},{
print("main task 2")
},{
print("main task 3")
}
], complete: {
print("main task done")
})
// background 에서 모든 작업 실행 후, main에서 completion
DispatchQueue.global(qos: .background).async(execute:
[
{
print("background task 1")
},{
print("background task 2")
},{
print("background task 3")
}
], complete: {
print("background task done")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment