IOS DispatchGroup

DispatchGroup

A group of tasks that you monitor as a single unit.

Groups allow you to aggregate a set of tasks and synchronize behaviors on the group. You attach multiple work items to a group and schedule them for asynchronous execution on the same queue or different queues. When all work items finish executing, the group executes its completion handler. You can also wait synchronously for all tasks in the group to finish executing.

Sample code: (enter/leave/wait/notify使用)

    override func viewDidLoad() {
        super.viewDidLoad()
        let group = DispatchGroup()
        group.enter()
        fetchApi(serialNumber: 1) { serialNumber in
            print(serialNumber)
            group.leave()
        }
        group.wait()
        group.enter()
        fetchApi(serialNumber: 2) { serialNumber in
            print(serialNumber)
            group.leave()
        }
        group.notify(queue: DispatchQueue.main, execute: { print("notify")})
    }
    
    func fetchApi(serialNumber: Int, callback: @escaping (Int) -> Void) {
        DispatchQueue.global().asyncAfter(deadline: .now() + 2) {
            callback(serialNumber)
        }
    }

補充:

DispatchGroup和DispatchSemaphore的差別:

Use a semaphore to limit the amount of concurrent work at a given time. Use a group to wait for any number of concurrent work to finish execution.

https://stackoverflow.com/questions/49923810/when-to-use-semaphore-instead-of-dispatch-group

Ref:

https://developer.apple.com/documentation/dispatch/dispatchgroup

https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/ios-30-dispatch-group-%E8%99%95%E7%90%86%E5%A4%9A%E5%80%8B%E9%9D%9E%E5%90%8C%E6%AD%A5%E6%93%8D%E4%BD%9C-583fe2225a8f