In this blog, we will learn about dispatchgroup
Introduction
Dispatch groups allow us to monitor multiple tasks as a single unit. All set of tasks and synchronizes behaviors in the group. We add tasks to a group by making balanced calls to enter() and leave(). When all tasks finish executing, the group executes its completion handler. You can also wait synchronously for all tasks in the group to finish executing.
It will help the developer to execute multiple tasks at the same time
you will get the result synchronously when the task will complete it will notify that the task has complete
for example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
var groupqueue = DispatchGroup() groupqueue.enter() multiplecall(name: "test1") groupqueue.leave() groupqueue.enter() multiplecall(name: "test2") groupqueue.leave() groupqueue.enter() multiplecall(name: "test3") groupqueue.leave() groupqueue.enter() multiplecall(name: "test4") groupqueue.leave() groupqueue.enter() multiplecall(name: "test5") groupqueue.leave() groupqueue.enter() multiplecall(name: "test6") groupqueue.leave() func multiplecall(name: String){ print(name) } |
In the above example, enter() will initialize the dispatch group for the test1
once the operation starts then enter function will call and when it will complete then leave fuction will executed
all functions will call separately if some function takes some extra time then another function will be executed
if you have only one function then no need to call the dispatch group
this thing will happen with the API call also
in the case of the API
1 2 3 4 5 6 7 |
apicall(data: "test"){ apicall(data: data){} } func apicall(data: String){ completion(true) } |
Please click here to check more detail about it
In the above example if API call depends on another api response then this case will better solution
I hope this blog will help you to understand DispatchGroup, if you have any queries, comments, questions, or recommendations, feel free to post them in the comment section below!
For other technical blogs, please click here.