MarksCode
MarksCode

Reputation: 8604

Can I use dispatch group not in a loop?

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?

Upvotes: 0

Views: 908

Answers (1)

shallowThought
shallowThought

Reputation: 19602

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
}

Upvotes: 3

Related Questions