Dispatch Groups in Swift 5: iOS Concurrency (2020 Xcode 11, Swift 5)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] [Applause] what's up you guys welcome back to another swift video uh in today's video we're going to continue our look at concurrency and dispatch last video we took a look at dispatch queues and what they are kind of the little nitty gritties about them and in this video we're going to look at dispatch groups so here we are on apple's developer documentation website and basically the definition of a dispatch group is a group where you can aggregate dispatches surprise so the name is pretty indicative of what it actually does it's a pretty important concept it's pretty common in applications especially those that fetch data from an api so we're going to take a look at this we'll start on the playground like we did last time to just understand what it is and then we'll hop into a xcode project to see more of a realistic example and dispatch groups in action so that said make sure you absolutely destroy that like button down below for the youtube algorithm make sure you also destroy that subscribe button too i've noticed that over 70 of you that watch these consistently are not subscribed so make sure you hit that while you're at it let me stop going on and on let's jump right into the video quick pause before we get into the video if you haven't seen it already i am hard at work putting together ios academy.io a community where all of us ios engineers can come together learn how to build some of the top apps like facebook youtube and instagram in addition to interview prep to land some of these ios roles at top tech companies so if you're interested in the free and premium content to come head on over to ios academy dot io and enter your email address in the waitlist form and you will be notified as content becomes available that said let's get into the video alright so let's get started by creating a playground here and we're going to stick with the blank playground go ahead and save it wherever you'd like and let me expand this window once execute decides to stop being slow as per usual so let's move this over here and let's take a look at some dispatch groups so the first thing that i'll mention is if you're not familiar with dispatch queues in general take a look at the video i posted yesterday about dispatch queues kind of what they are what the heck they're used for and why they're a really important fundamental and they come back to this video so you can look at dispatch groups so dismayed groups as the name imply is a way of grouping dispatches together and observing when multiple dispatches come back and they're all done so what the heck does that mean so let's say you have some work that you'd like to do so let's say we have a function uh get data and let's say we have an array of urls we'll just say array uh let's call those urls and we'll just use strings for now because i'm lazy let's say one we'll pretend these are urls and let's say we wanted to fetch data from each of these urls let's call let's say their api urls and actually let me just not be lazy and let me do this so hypothetically if these were url endpoints and let's say we wanted to get json data from each of them and that we only wanted to update the user interface once all three of the network requests have come back so a simple solution to this would be make three functions with each of them taking a completion handler and call them linearly one after another so once this one is done save the result and then call this one and then once this one is done call this one and then after that call the ui update function a problem with that rather an inefficiency with that is you need to wait to call the next one and once this one is done so it adds a little bit of latency to your dispatches of work and that work in this case being fetching data so there's this thing called dispatch group and let's take a look at it so to create a dispatch group you basically just construct a dispatch group and the benefit of this is you can actually run a for loop and you can tell for each operation that you're starting that the dispatch group has entered an operation and once that operation ends you say dispatch group i've left the operation and then at the end of the for loop you can put a callback which basically says notify me when everything that has entered has left the operation group and that's how i know that we are done with everything we being the system so in this case we would say uh group.enter for each of the network calls that we dispatch to get data and once we get the data back we're going to say group.leave and that's how we're going to know that's how we're going to notify the dispatch group hey we're done with all three operations you're good to go in terms of updating the user interface so the way this would look is for url and urls again we're going to create a very basic uh network task with a url session and i stuck with this example in the first video on dispatch queue since it's a very very common one and i think it's the easiest one to understand so we're going to do a data task with a url and a completion pass in the url and this completion takes in data response error let's create that url so we can say guard lat url is url with the url string if it fails we'll continue to the next for loop iteration and then we need to say task.resume which just kicks off the task so now we need to place in the calls to the group so we've created a group here and this warning is yelling at us that we have a group and it's a constant but we never used it so we're going to say every single time you run the for loop and once we validate the url exists we're going to say group dot enter and because the completion handler on this url session data task is asynchronous in other words we don't know when it's going to return because we're getting stuff from the internet from a network call and the network might be slow or it might time out or what have you we're going to put in here in a deferrer block and defer basically signifies that the code execution is leaving the scope once this uh this completion has gotten called and executed we're going to say group dot leave and then outside of the for loop we're going to say group dot notify and there's two versions in here and this is the one i like to use the first parameter of this is on what queue do we want to be notified and again if you're not familiar with this i covered in my last video and the common ones that people use are either the main thread or the main queue or the global cue and you can optionally provide a quality of service but we're going to stick with the main cue in this case because we're fetching data in our hypothetical scenario we want to update the user interface once we get everything returned and this closure gets called once everything is returned and it will get called on the main queue so we'll say something like update user interface and let's see why this is complaining uh this is complaining replace defer with do so it's complaining because we're not really doing anything in here but hypothetically we can uh we can put stuff in there in the application that we're gonna do in a second see now it's complaining we're not using the data but uh let's just do a print of the data so it stops annoying us but basically the the takeaway from this is instead of having multiple functions of completion handlers you can create this group object and every time we iterate we basically tell the group that we're entering some work and once the completion asynchronously comes back we'll say we're leaving that work and because we run the for loop three times because url and urls there's three of these in here we'll enter the group three times and we'll leave the group three times and then this notify thing is basically saying once the group has evened out aka you entered three times and you've also left three times regardless of the order that they have entered they don't need to be linear so long as everything that has entered has also left we're going to notify on the main queue to do whatever code execution that we have in this block which would be something like a user interface update so a practical example of this that i can speak to you firsthand is in the youtube app when you open it up or even like instagram sometimes what they do is they'll dispatch on dispatch group to fetch data from multiple tabs even though you're not on another tab you're launched to the main home tab and the reason they do this is because a it's efficient and b a lot of the data that drives one user interface and one of the tabs is also related to the other tab so instead of making the user wait for a spinner every single time they load and cache things babying those apps so now that this is uh hopefully a quick little primer let's jump into xcode in a real project and let me try to mock a example for y'all and let's see if that helps in understanding this better so we're going to create a very basic single view application and i'm going to go ahead and call this dispatch groups we'll just call them my dispatch groups sure let's save it to the desktop and we're gonna select a simulator to build and run into so go ahead and pick a simulator of your choice command r get that open let's also expand this xcode window to give ourselves a little more room to work and we're going to pop into our view controller file here and do a quick example so the example that i'll do is similar to what we just looked at in the playground but instead of actually fetching data because i don't want to have to go and kind of dig up an api and you know do all the codable model stuff what i'll do is i'm simply going to use a weight parameter to mock as if we're waiting for data to come back so i'm going to create a function called get data and what we're going to do is we're going to create an array and this is going to be an array of integers and this the numbers in here are going to signify how long we're going to wait in each uh dispatch so we're going to say something like 1 3 5 six two and let's say ten yeah let's do seven just so you guys have to wait that long and what we're gonna do in here of course is we're gonna call get data we're gonna create a dispatch group like we did in the playground looks the exact same and we're going to say for number in array we're going to say group dot enter and then what we're going to do is we're going to create a delay block just to kind of show that the work that happened came back in n number of seconds and we're going to use the number to signify how long we're waiting and to use dispatch q to simulate uh waiting for something you can simply say dispatch queue if i can spell it correctly dispatch q dot global dot async after and we're going to wait basically now plus the number of seconds so now plus number and then we are going to execute some work and that work is going to be group group.leave like so and let's see why this is complaining this is complaining because we're saying now plus number and i think this needs to be a time interval actually so let me go ahead and change that doesn't want to integer needs to be a time interval type like so and that should stop complaining hopefully yeah it looks like that warning went away and basically once uh once the delay time has uh elapsed we'll come in here and call dispatch group uh leave and then after this for loop similar to our playground we're gonna say group dot notify and we're gonna notify on the main thread that we are done we're going to first do a print done with all operations and we're also going to spell print correctly just kidding because i can't spell ever we're going to say self.view.backgroundcolor and we're gonna assign it to be let's make it blue kind of irrelevant and let me add some more prints in here so i'm also gonna do a print starting uh let's say entering group just to make it more uh indicative of what's going on entering group with number and we're just gonna gonna uh interpolate the number in here like that and then we're gonna say print leaving group for number and let's go ahead and run this now the important thing you'll see in the print statement is the order of numbers in here of one three five seven two seven will not be linear because obviously the thing that takes one second let me close up my virus pop-up the thing that takes one second will come back faster than the thing that takes um seven seconds the two will come back next is two seconds and then three then five and the seven seven will come back at the same time so you'll see the prints in a second and that will probably help clear up this example in a real world use case so let's go ahead and open up our console you can hit command shift y to do that let's close up this left panel and this right panel whoops not notification center that's not what we want and go ahead and hit command r to build and run and okay so it looks like everything got executed and things are coming back slowly in the leave and then once we're done with everything once the group is notified that every single thing is done which this whole thing changes to blue because we said self. uh view background color is blue so if you take a look at the prints in here the order that we actually started entering for the groups matches the order of our array up here so let me zoom out you can see both and the reason is is because we do a simple for loop and we enter in the order of the array however we don't end in that order so we first end with one second and then two second three five seven seven and the reason is is because obviously we're using this as kind of a delay for the time that has elapsed but in the point that i want to illustrate is when you're dispatching work like multiple network fetches there's no guarantee of the order that it's going to come back now there are ways you can set it up where you want one to come back and then do the next one but in this case that's not how you would do it and once all of the operations have uh left so this is now zero so we entered the group six times i believe and then we also left the group six times uh basically all operations are done and we can go ahead and notify in this case to the main cue go ahead and do that print as well as update the views background color so this is a very common paradigm that's very often used in large applications and even smaller applications it makes your code more efficient rather than running requests kind of linearly and is definitely a very popular interview question so definitely don't don't cut corners around dispatch groups and concurrency it'll come bite you in the end so that's it that's all i had for you guys today if you haven't smashed that like button already make sure to do so for the youtube algorithm i also noticed that over 70 percent of you that consistently watch these videos don't subscribe so hit subscribe while you're at it uh if y'all subscribe it kind of motivates me to make more of these videos and series and i encourage everyone that actually kind of cares to subscribe and if you have any feedback i'd love to hear the feedback so i can make these more valuable for you a big part of me makes these videos because you know over 10 years ago i got my start here on youtube as well and this is a little bit of me paying it forward and i love helping each and every one of you out with your projects and applications so you guys tell me what you need and i'll make sure that i put out content that suits your guys's interests and needs so thank you so much for watching i will see you guys in the next video
Info
Channel: iOS Academy
Views: 14,068
Rating: undefined out of 5
Keywords: swift 5 dispatch group, swift 5 tutorial, swift 5 for beginners, swift 5 threading, swift 5 concurrency, swift 5, swift, swift gcd, swift dispatch async, dispatch queue swift, dispatch group swift, how to use dispatch queue in swift, swift make app, learn to make app swift, what is swift and xcode, xcode 11 2020, swift development 2020, swift xcode 11, swift for beginner, swift learn to make app, threading in swift, swift sync vs async, swift closures, swift operations, app
Id: 4zsNgBhDs0M
Channel Id: undefined
Length: 17min 33sec (1053 seconds)
Published: Sun Jul 05 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.