Dispatch Group in Swift

emre gürses
2 min readApr 6, 2023

How you can wait for 2 asynchronous requests to complete before proceeding

In Swift, Dispatch Group is a tool for synchronizing the execution of a set of blocks. It allows multiple blocks to be submitted to a queue, and it tracks the completion of these blocks so that you can wait until they have all completed. Dispatch groups can be used to coordinate the completion of asynchronous tasks and to wait for a set of tasks to complete before continuing. The DispatchGroup API is part of the Grand Central Dispatch (GCD) framework and is used to manage the dispatch queues in Swift.

Here is an example in Swift that shows how to use a dispatch group to wait for two asynchronous requests to complete before proceeding:

let dispatchGroup = DispatchGroup()

// First asynchronous request
dispatchedGroup.enter()
makeAsyncRequest1 { response1 in
// Handle response from first request
// ...

dispatchedGroup.leave()
}

// Second asynchronous request
dispatchedGroup.enter()
makeAsyncRequest2 { response2 in
// Handle response from second request
// ...

dispatchedGroup.leave()
}

// Wait for both requests to complete
dispatchedGroup.notify(queue: DispatchQueue.main) {
// Both requests have completed, continue with next task
// ...
}

In this example, we first create a dispatch group using let dispatchedGroup = DispatchGroup(). Then, for each asynchronous request, we use dispatchedGroup.enter() to indicate that we have submitted a task to the dispatch queue. After the response is received, we use dispatchedGroup.leave() to indicate that the task has completed. Finally, we use dispatchedGroup.notify(queue: DispatchQueue.main) to specify a block that should be executed after both requests have completed. The block in the notify function is executed on the main queue, but you can specify a different queue if you need to.

--

--

emre gürses

Denizbank — Intertech, Mobil Uygulama Geliştiricisi(iOS)