Suppose you have multiple threads running. Each thread is doing one task. You want to get notified either on the mainThread OR another thread, when all the task-threads are completed.
The simplest solution to such a problem is a DispatchGroup.
When using a DispatchGroup, for each request, you enter the group and for each completed request, you leave the group.
When there are no longer requests in the group, you will be notify (notified).
With the above, you don't have to wait infinitely until all the tasks are completed. You can display a loader BEFORE all the tasks have started and dismiss the loader AFTER all tasks are completed. This way, your main thread does not get blocked and your code remains clean.
Now suppose you also wanted the tasks to be ordered or add their responses to an array sequentially. You could do the following:
Every entry must have an exit in a DispatchGroup. If you forget to leave after entering, you are setting yourself up. You will NEVER be notified when the tasks are completed.
The amount of enter must equal the amount of leave.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0