Can I use dispatch group not in a loop?

送分小仙女□ 提交于 2019-12-12 01:14:58

问题


Say I have 3 different asynchronous tasks I want to get done before calling some function. I'm aware of using dispatch groups to do such a thing if those tasks were in a loop,

    var dispatchGroup = DispatchGroup()

    for task in tasks {
        dispatchGroup.enter()

        DoSomeTask { (error, ref) -> Void in
            dispatchGroup.leave()
        }
    }

    dispatchGroup.notify(queue: DispatchQueue.main, execute: {
        DoSomeFunction()
    })

However, I'm confused on how you'd do this if those tasks were all in the same function but didn't have to do with eachother, like pushing 3 different values to your database. Something like this:

   updateDatabase() {
        var dispatchGroup = DispatchGroup()

        DoTask1 { (error, ref) -> Void in           
        }

        DoTask2 { (error, ref) -> Void in           
        }

        DoTask3 { (error, ref) -> Void in        
        }
   }

Where would you put the leave and enter statement in such a case as this?


回答1:


In this case your updateDatabase() function needs a completion block that you call after all update are done:

updateDatabase(onSccess completion:() -> Void) {
    var dispatchGroup = DispatchGroup()

    dispatchGroup.enter()
    DoTask1 { (error, ref) -> Void in   
        dispatchGroup.leave()        
    }

    dispatchGroup.enter()
    DoTask2 { (error, ref) -> Void in           
        dispatchGroup.leave()
    }

    dispatchGroup.enter()
    DoTask3 { (error, ref) -> Void in        
        dispatchGroup.leave()
    }

    dispatchGroup.notify(queue: DispatchQueue.main) {
        completion()
    }
}

You than call it like this:

updateDatabase() {
    //do somthing after updating
}


来源:https://stackoverflow.com/questions/41869831/can-i-use-dispatch-group-not-in-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!