Sobes.tech
Junior — Middle

How is synchronization of multiple asynchronous tasks achieved using DispatchGroup?

sobes.tech AI

Answer from AI

DispatchGroup in iOS is used for synchronizing multiple asynchronous tasks. It allows tracking when a group of tasks has completed.

How it works:

  1. An object of DispatchGroup is created.
  2. Each asynchronous task is added to the group using group.enter() before starting and group.leave() after finishing.
  3. You can call group.notify(queue:) to execute a block of code after all tasks in the group have finished.

Example:

let group = DispatchGroup()

group.enter()
DispatchQueue.global().async {
    // Asynchronous task 1
    print("Task 1 started")
    // ... work ...
    print("Task 1 finished")
    group.leave()
}

group.enter()
DispatchQueue.global().async {
    // Asynchronous task 2
    print("Task 2 started")
    // ... work ...
    print("Task 2 finished")
    group.leave()
}

group.notify(queue: DispatchQueue.main) {
    print("All tasks completed")
}

Thus, DispatchGroup helps wait for the completion of multiple parallel operations and execute subsequent code.

How is synchronization of multiple asynchronous tasks… - sobes.tech