Sobes.tech
Junior — Middle

Can you list and explain the main methods of working with DispatchGroup in iOS?

sobes.tech AI

Answer from AI

DispatchGroup in iOS is used for grouping multiple asynchronous tasks and tracking their completion. Main methods and ways to work with DispatchGroup:

  • enter() — informs the group that a new task has started. Should be called if the task is started manually and not through group.async.
  • leave() — informs the group that a task has finished. The number of leave() calls should match the number of enter() calls.
  • notify(queue: DispatchQueue, execute: () -> Void) — sets a block of code that will execute on the specified queue after all tasks in the group are completed.
  • wait(timeout:) — synchronously waits for all tasks in the group to finish or until the timeout expires.

Example of usage:

let group = DispatchGroup()

let queue = DispatchQueue.global()

group.enter()
queue.async {
    // Asynchronous task 1
    print("Task 1 started")
    sleep(2)
    print("Task 1 finished")
    group.leave()
}

group.enter()
queue.async {
    // Asynchronous task 2
    print("Task 2 started")
    sleep(1)
    print("Task 2 finished")
    group.leave()
}

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

In this example, two tasks run in parallel, and after their completion, a block in notify is called. This approach allows convenient synchronization of multiple asynchronous operations.

Can you list and explain the main methods of working… - sobes.tech