DispatchGroups to group API calls in Swift

Need to make multiple network calls for your ViewController? We can use DispatchGroup, and this article explains why.

Image for post
Image for post
I guess it’s a group?

Basically you can add work to a group, which then can be executed asynchronously than you can run a closure once they are finished.

Now of course it is possible to wait synchronously for a series of API calls to complete, then synchronously run whatever you want. But you’d rather do things the right way, right?

Difficulty: Easy | Normal | Challenging

Prerequisites:

Terminology

DispatchGroup: A group of tasks to be monitored as a single unit

Synchronous: the thread that initiated that operation will wait for the task to finish before continuing. This means that tasks assigned synchronously run in order. If performed on the main thread, this means that the UI can be blocked which means that users of your software might feel that is has crashed — this is very bad! Of course this actually applies to whichever thread you run the process on, so usually activities like network calls are best made asynchronously

Creating a DispatchGroup

For this tutorial, we are going to use the name “waitingGroup”

let waitingGroup = DispatchGroup()

A gotcha

Enter the queue

waitingGroup.enter()

This is run before our target async closure

Perform the task and exit the queue

wait(delay: 1) {

waitingGroup.leave()

}

where the wait function would be

func wait(delay: UInt32, completion: () -> Void) {

sleep(delay)

completion()

}

After the task(s) are done

waitingGroup.notify(queue: .main) {

print(“done”)

}

Conclusion

The repo

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store