DispatchQueue in Swift 5: iOS Concurrency & Threading (Xcode 11, 2020, swift)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] [Applause] what is going on guys welcome back to another Swift tutorial in today's video we're gonna be looking at a basic primer to dispatch cue and concurrency in iOS so this is a really important concept that a lot of people struggle with and it's so so important I can't stress it enough and it's very very common in interviews and I think rightfully so so here we are on Apple's own documentation about dispatch queue there's a bunch of things in here we're gonna take a look at the core difference between the main queue and a global queue with various background quality of services but a quick high-level kind of overview what the heck this thing is I'm not gonna read this to you guys you can google it but basically in any software application you need to execute your code either on the main thread or in a background fashion so you can imagine any type of user interface update you want to do is on the main thread and any type of data fetching you want to do should be a background job so with that in mind let's smash that like button down below together for the YouTube algorithm get excited get execute ready and let's jump into a playground to get started quick pause before we get into the video if you haven't seen it already I am hard at work putting together iOS Academy i/o 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 tool and 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 IO and enter your email address into the wait list forum and you will be notified as content becomes available that said let's get into the video alright so we're gonna first start in a playground and then once we get a good fundamental understanding of what Dispatch queues are we'll jump into a project and look at two real-world applications so I'm gonna start by creating a playground well with a blank playground we can leave the default name and once Xcode decides to stop being slow we're gonna expand our window and get into it I love how echo this has to be slow in all of my videos but here we are so let's zoom in a little bit here and let's start talking about dispatch queues so the big thing that I really briefly touched on the beginning of the video is the concept of understanding the main thread versus background thread and threading is abstracted away from us Apple developers whether you're building for Mac OS or iOS and watch OS and they're abstracted to this thing called dispatch queues and dispatch queues basically allow you to submit code execution to either a main queue or a background queue and Apple basically execute that queue work in that format whether it's main or background so let's just see what the syntax looks like so if we want to do some work let's create a function called foo and if we want to do some work on the main thread we would save dispatch Q dot main and we're gonna say async you could actually do sync here also now I'm not gonna cover the difference in this video because it's gonna get a little long but basically we can call this foo function in here and we have to say self dot because this is a closure and this function gets executed on the main queue so that's the basic syntax of it and we'll discuss what the heck this means in two seconds and this is complaining because we actually don't need it in the playground but in a application we will need it but similarly let's take a look at dispatch queue for a background queue so we're gonna say dispatch queue and we're gonna say global async and we can again a call foo so a background q actually leverages the global queue Apple provides and the work that we do in here we can actually provide a quality of service parameter QoS and you can basically specify to Apple what level of importance what quality of service do we want for the work gonna be executed in this block right so if you look at the options here and the associate descriptions which I guess are not showing up in this case and the actual Xcode project will show up you have things like user interactive user initiated defaults background utility I don't know why they're redundant down here but they're the same ones that are up here but basically if you have work that's initiated by the user like something where the user initiated some task the system logically the name implies will prioritize the work executing here because the system knows the user initiated it however it'll still be done in a background fashion whereas anything done on the main queue is done almost immediately so if you guys don't have to guess all user interface updates are they on the main queue or the background queue and the answer is the main queue and the reason for that is when a user is swiping or tapping or touching or anything on your actual display of your iPhone iPad or whatever you never want the experience to be choppy so you want to always do UI stuff on the main thread and whenever you have operations going on like downloading data sectioning images any type of async operation where you're basically calling something and expect a completion to come back those types of jobs use a global queue and specify generally a quality of service most often than not it's just background and the reason you do that is because you can basically dispatch that workload to kind of behind the scenes and once it's done we can dispatch any UI updates back to the main thread so let's say we were fetching some type of data so like fetch data from API and then once we have the data let's say we wanted to update some label or some user interface once we have the data we could call back to the main thread and say update UI so you could technically call the update UI code here as well however you'll see warnings in your console in addition to not necessarily getting those user interface updates appearing on your device right away and the reason is like I mentioned main thread is prioritized because it's your main and this is running in the background so this this concept of concurrency is extremely important it's the fundamental of any software application and it's a super super popular interview question especially if you want to get into the likes of Google Facebook Microsoft this is such a fundamental so that said let's actually close up this playground hop into a Xcode project and we're gonna see a real-world application and how the heck this actually plays out in a real project so I'm gonna stick with a single view application will call this iOS concurrency and we can stick it on our desktop and looks like I got a duplicate one cuz I was testing something before this video will go ahead and replace it that's okay and let's go to our view controller and look at a real world example so oftentimes in our applications we need to fetch data from an API and show it on the user interface and that looks something like the following so let's say we have another function that is called get data and in here we have a URL session task so we're going to say let task equals URL session shared and you want a data task with a URL and completion which is this first one here will say URL and the completion takes data response and error now let me go ahead and close up this right panel just to give ourselves a little more room to work and let's also put this back to the one line let's create that URL up here we'll say guard what URL is a URL and we're gonna create it with a string this is kind of irrelevant for the purposes of the video but let's just create a URL like that and basically once we create tasks and we do resume on it which kicks it off we get this completion handler as a part of this URL session data task and this is where our data will come in and we need to unwrap the data and all that good stuff but oftentimes like I mentioned once you get the data you want to reflect it on the user interface and an example that you can think of is like the YouTube app when YouTube launches up they need to go and fetch all the information about videos so they can render it so in here you would do something along the lines of guard let data equals data else you can return and let's say you have data in our case we'll do self dot view dot background color and we'll just make a red and let's just say data does not equal nil otherwise we'll get that warning that we're not using the data variable and basically we're now calling this function and let's see if we have any error looks like we don't and in viewdidload we would call basically this get data function and there's a couple of problems with this code so the first thing let's walk through what's actually going on so we have a review controller right and viewdidload gets called once the view for this controller has loaded which does not necessarily mean actually it does not at all mean that the view is on-screen it just means it has loaded into memory once it has loaded we kick off this function for and get beta once get data is called we create this URL session data task with a URL pass it in it's an empty URL in our case we provide a completion Handler and once the data comes back in the completion handler what we go ahead and do is we update the background color of our view so there are two problems going on here the first one is we're calling self dot view in here and that causes a memory retention cycle so we need to say weak self and if you're not familiar with what this is I just posted a video about this yesterday so go ahead and take a look at that and because we did weak self we now need to do self optional just so we don't cause a memory retain a cycle but in regards to dispatch queue and concurrency the issue that we're doing or that we're causing here is this completion handler actually gets executed on a background thread and we're trying to update the user interface onset background thread and the problem with that is like I mentioned in our playground a background thread is not executed immediately it happens as a lower priority as opposed to the main thread because everything on the main gets prioritized for the user interface so what we actually need to do to fix this is explicitly say update the UI this UI property of color on the main thread so we would say dispatch queue main dot async it throw that code in there and now this is functionally correct as well as in terms of your threading and concurrency so why is this correct the reason it's correct like I mentioned is on the main thread we call this do this get data get data invokes this URL session data task but the completion Handler of the task occurs on the background thread and once that occurs and we get some data back we dispatch back to the main thread and say hey update the UI color so you might be asking how do I know that this happened on the background thread and it's a really good question and oftentimes people never learn the answer to this question and the answer is quite simple the answer is if you think about it logically when you want to get data from somewhere do you just want to sit there and wait for the data or do you need to dispatch it and after n number of seconds you may or may not get data and the answer is the latter so when you open up let's say Gmail or any app you oftentimes see a spinner and it takes some time to get the data and the nature the completion Handler is call it the function will call the completion handler once the data has been returned and once the data is back you can use it but this is the reason it's a synchronous and on a background thread and we need to dispatch it back to the main red or main cue as the proper terminology is shown here so the rule of thumb is whenever you have in a synchronous style block like this for a closure it's probably a good idea to assume that it is on a background thread especially when you have something that's dealing with networking which is by far the most common example and yeah that's basically this example here is by far the most common one you'll see in interviews you'll see it in your day to day jobs if you work as a iOS dev full-time you'll see it in your personal projects so on and so forth so that said let me just do one other thing so if you let's say wanted to call some work on a background thread explicitly and we did this in the playground I'll just do it here too let's say we want to call background work and here we can do a call background work you could do in here as you can save this batch queue main whoops dismiss cute global and async and you can do stuff here and let's say you wanted to dispatch this with a particular quality of service and here are those descriptions I was talking about in the playground where you can see what each one is meant to be used for so this tells you the quality of service for this class of tasks is related to this whole thing blah blah blah so it basically tells you like what each one is meant to be used for and Apple manages the priority and the kind of hierarchy of which stuff to get done first because the system is doing several jobs concurrently so it'll manage all the for you based on the quality of service that you specify so that said that's actually where I'll wrap up the video like I said it's a very quick primer to dispatch queue and concurrency in iOS I actually have a couple other videos planned about things like dispatch group NS operation queue and a few other fundamentals about concurrency as it's a very important concept and I also personally think it's pretty interesting once you get into the weeds of it so that's it if you haven't smashed like but I'm already please make sure to do so for the YouTube algorithm subscribe if you're new while you're at it if you enjoyed the video if you have any questions comment them down below thanks for watching I'll catch you guys in the next one
Info
Channel: iOS Academy
Views: 18,355
Rating: undefined out of 5
Keywords: swift 5 dispatchqueue, swift dispatch queue, swift 5 for beginners, swift concurrency, dispatch queue swift ios, operation queue ios, threading swift 5, dispatch groups swift, swift development, how to make app in swift, make first swift app, swift threading, swift main thread, swift main queue, swift beginners, intro to ios and swift, how to make iphone app, what is GCD, grand central dispatch swift, swiftui dispatch queue, make app in swift, swift for beginner, make app
Id: hmu0v_25pgc
Channel Id: undefined
Length: 15min 43sec (943 seconds)
Published: Sat Jul 04 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.