Dispatch Group in Swift

Tram Ho

Hello everyone, today I will write about Dispatch group in Swift. The Dispatch group allows you to group multiple tasks together and wait for them to complete or receive a notification when they are finished to continue your login. These tasks can run asynchronously or asynchronously and can run on many different queues. For example, when opening a screen, you need to call multiple APIs to get data, after finishing calling all these APIs to update the data on the interface.

The Dispatch group provides the wait () function, which blocks the current thread until the tasks in the group are completed. Usage of dispath group is as follows:

Explain:

  1. Because using .wait () is currently blocked by the thread, so I use async to put the whole function on the background queue, so that it does not block the main thread.
  2. Create a dispatch group.
  3. Call the enter () method to tell the dispatch group that a task has been started. Make sure the number of enter () is equal to the number of leave () calls, otherwise the app will crash.
  4. Call the enter () method for the second task.
  5. 5a. 5b. Call the leave () method to notify the dispath group that the task has finished.
  6. Call the wait () method to block the current thread while waiting for the task to complete. We can use wait (timeout:) to specify the waiting time to avoid waiting too long.
  7. At this point, all the tasks are done or timeout, I reload the data of the tableView in the main thread.

Using wait () is not a good solution because it has to block the current thread. A better way is that the dispatch group can notify you when the task in the group is completed. I changed the above code as follows:

In this implementation, I do not need to put the code in the background queue because using notify does not block the current thread.

  1. The dispatch queue will notify us when the tasks in the group are completed, we update the UI in the main thread.

Hope the article can help you when learning about dispath groups. Thank you for reading this article ?

Share the news now

Source : Viblo