Sobes.tech
Middle

What is a dispatch group in the context of iOS development?

sobes.tech AI

Answer from AI

DispatchGroup is a mechanism of GCD (Grand Central Dispatch) that allows tracking the completion of a group of asynchronous tasks and executing an action after their completion. It is useful when coordinating the work of multiple dispatch queues or threads.

Main methods:

  • enter(): Notifies the group that a task has started. Increases the group's internal counter.
  • leave(): Notifies the group that a task has finished. Decreases the counter.
  • wait(): Blocks the current thread until the group's counter reaches zero or a timeout occurs.
  • notify(queue:execute:): Registers a block of code that will be executed asynchronously on the specified queue when the group's counter reaches zero.

Example of using notify:

import Foundation

let group = DispatchGroup()
let queue = DispatchQueue.global(qos: .userInitiated)

queue.async(group: group) {
    // First asynchronous task
    print("Task 1 is running...")
    Thread.sleep(forTimeInterval: 1)
    print("Task 1 completed.")
}

queue.async(group: group) {
    // Second asynchronous task
    print("Task 2 is running...")
    Thread.sleep(forTimeInterval: 2)
    print("Task 2 completed.")
}

// Execute this block after all tasks in the group are finished
group.notify(queue: .main) {
    print("All tasks in the group are completed.")
}

// For demonstration of non-blocking nature of notify
print("Code after adding tasks")

Alternative example with manual enter() and leave():

import Foundation

let group = DispatchGroup()
let queue = DispatchQueue.global(qos: .userInitiated)

group.enter() // Task 1 started
queue.async {
    print("Task 1 is running...")
    Thread.sleep(forTimeInterval: 1)
    print("Task 1 completed.")
    group.leave() // Task 1 finished
}

group.enter() // Task 2 started
queue.async {
    print("Task 2 is running...")
    Thread.sleep(forTimeInterval: 2)
    print("Task 2 completed.")
    group.leave() // Task 2 finished
}

group.notify(queue: .main) {
    print("All tasks in the group are completed (notify).")
}

// Example of using wait (blocking)
// group.wait()
// print("All tasks completed (wait).") // This code will execute after all tasks are finished, blocking the current thread.
What is a dispatch group in the context of iOS… - sobes.tech