Call completion block when two other completion blocks have been called

后端 未结 2 1309
独厮守ぢ
独厮守ぢ 2020-12-11 22:08

I have a function doEverything that takes a completion block. It calls two other functions, doAlpha and doBeta which both have complet

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 22:45

    Ahmad F's answer is correct but, as my functions with callbacks return immediately (like most do) and the callbacks are executed later, I don't need to create a new queue. Here's the original code with changes to make it work.

    func doEverything(completion: @escaping (success) -> ())) {
        var alphaSuccess = false
        var betaSuccess = false
    
        let group = DispatchGroup()
    
        group.enter()
        doAlpha { success in
            alphaSuccess = success
            group.leave()
        }
    
        group.enter()
        doBeta { success in
            betaSuccess = success
            group.leave()
        }
    
        group.notify(queue: DispatchQueue.main) {
            completion(alphaSuccess && betaSuccess)
        }
    }
    

    I didn't really want to force the completion call onto the main thread, but hey ¯\_(ツ)_/¯

提交回复
热议问题