Async/Await in action (Swift 5.5)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

iOS15 only right ? :(

👍︎︎ 1 👤︎︎ u/nalakme 📅︎︎ Jun 29 2021 🗫︎ replies
Captions
hello guys welcome to another video i'm really excited because today we will talk about one of the most weird features for 5.5 we are talking about async await let's explore today why this is so important and how we're going to change the way we called in swift forever let's start because yeah we have a lot of magic to cover here my name is pete and this this is if and [Music] tips all right let's start asking us why the community requires to introduce async await we have been for so long working without that right working with closures or external dependencies for example alex swift promise kit or recently in ios 13 combined in fact let me explore in detail here what we are doing to get the information provided in this pokedex demo by the way if you want to know more about this pull to refresh action and for example this task or even more about async image i strongly recommend you to watch my previous video about what's new in swift ui 3.0 because it's the base of this demo so we're going to focus today on the business logic to make this possible anyway this is working right now the magic it's actually located in this loaded dot load this function is executing or called to the api let's see what's inside and actually it's just calling other function which is combined load as you might guess this load action is using combine under the hood this example could sounds familiar because we talk in detail about it in or combining video however yeah here we are using combine for a reason because combined is giving us some flexibility to organize or process in what kind of actions we want to do for example you know getting the response the coding et cetera but today we won't talk so much about combined in fact another question yeah we're using combine here but why that's because without order external dependency or first body dependency like combined our only option is just to use closures to execute this kind of behavior so for that let me transform this example using combine with only closures and see why we need to use other techniques or what used to do that because now we will see the power of async weight in just a moment okay let's just ignore this for now and let's create the same load function but now using closures okay the first thing we need to use here is this url i am using this one that is the same that combined load function is using it's just here controlling the pagination to get different pokemons over and over now using closures the next thing you need to use is well in this case calling or api to do that we need to use url session and create a task that we will execute that action so let's create a text for that and we will execute this method that data task that it's requiring an url so the rest is just using the completion handler disclosure will provide the response once we execute that task to get the information from the network and if you remember this closure contains three parameters one is data which is the actual data that we received the response from that url that we tried to retrieve and the error if we got anything wrong all right now what we need to do is validate the possible situations with these three parameters the first one is just checking if we got an error okay let's try that and if we got an error the only thing we need to do is maybe well draw an error right throw this error actually no we cannot do that this is because this is a closure we are inside of closure and disclosure it's not using trolls keyword which means this closure cannot throw an error this is something really important so in that way we cannot propagate an error using throw our only way to do it is using another closure to propagate that and that closure should come from this parameter okay let's provide that closure let's mark this as escaping here we will use result objects from swift we will say that our success case will be retrieving a list of pokemon and we will return an error if something wrong happens okay now here we can then use completion and return failure and propagate the error okay we got the error but if we don't get any error we need to check if actually we got a status code of 200 let's see that okay if this is happening then something is wrong in the network then we need to return another kind of error but here what i'm going to send is one of the errors that we have here we have pokemon error and we will use server error now once we reach this else branch we are ready to finally get something from data but data it's optional so yeah we need to unwrap to see if we actually have something here otherwise we need to return an error and again send another error in this case let's use no data and don't forget to add this return because it's required in this guard statement okay we got our data now it's time to decode our data we will use json decoder this time we want to decode this data and transform it into a pokemon response object let's do that and again if we are not able to get anything yeah we are just returning no data all right after all this validation finally we can send our pokemon list let's use our success case here in this completion okay our success case here is then return that pokemon list so for that we need to use pokemonresponse.result which is the list of pokemons yay amazing however don't forget that you need to use task does resume pretty common mistake okay we are good here however uh we need to do something with this completion so yeah let's go back to load method and then call disclosure load there okay let's call disclosure and use here or completion handler let's use result and use a switch just to catch the different situations for the error just simply want to print the error and use self error which is a boolean method just to reflect that yeah we got an error now for success we need to use the list and here we will assign this list to our pokemon data which will be list reverse plus or previous data we are using just for you to get the idea and see really easy they pull to refresh action also don't forget to increase the offset for the by nature however we are getting access to self here inside disclosure so remember we need to capture yourself to avoid any routine cycle and of course do the guard led dance okay we are good to go right let's run this oh almost because yeah this thing is modifying the ui and remember that every action that is updating your ui needs to be in main track okay let's put this into a main you okay okay let's run this are we good now yeah we're good okay let's try the pult refresh action looks like everything is working okay but look how much code we had to use to just this simple pull to refresh and list operations oh my god it's a lot of boilerplate code also it's pretty easy to make mistakes for example here you need to make sure that you are sending the right completion because yeah if we don't do anything yeah this thing is compiling so there's no way for you to actually realize that you forgot something also you are handling result which is a kind of a boilerplate to say okay this is a failure error this is a failure of other errors so on so on and yeah this is just a simple closure but there are multiple situations in which one closure depends of other closure and other closure and so on and then you have a nested closure inside of other and that becomes even worse what is the problem that a single weight told well first of all this one avoid two nesting things over and over inside of an if inside of a closure inside of another closure so and so on that's one thing and second thing it's also try to make our code more readable because yeah this thing is really i mean again this is a really simple example and can you imagine a really really complicated example yeah will be even worse to follow that oh by the way also i need to remember that yeah you need also to use and complete your handler here and then you need to use you know if you're accessing to self-reference you need to capture it yourself and then you're making sure that everything is in main thread etc etc so yeah it's a lot of things a lot of preparation for your code to be ready okay let's change the approach now and use a single way okay now what we need to do here well again we need the url and now we need to use url session again but this time instead of using the closure we will use an asynchronous function let's see that yeah you have all these options here but also you have these two methods here but look the error here it says that yeah this is a sensing method and you cannot use an async method inside of a synchronous method what it means is that yeah by default this function is synchronous if you are not telling swift anything so in order to you to use any asynchronous function inside of this function the only thing you need to use is the word async per simple now swift will understand that this function is prepared to be asynchronous let's go back to theta and yeah we don't have that issue again so we are ready to go to use whatever function we got here in this case let's use this one with url we have the url so let's do it and for now we don't care about any delay now what is the return type of this this is simply returning a tuple of data and url response like a normal function like a synchronous function right it's pretty simple let's capture the result of this function into two variables let's use this one for data and let's use this one for response now in order to tell in swift that this function is asynchronous and you have to wait for this one because you don't know when this asynchronous function will finish you need to use a weight this is more or less like for example when you are marking a function that is trouble that will produce an error and sometimes you need to mark that function as throws right and then the caller needs to use try to reflect that okay i will try to do something but i don't know if this will produce an error or not it's the same way so this function is marked as a sink which means as is a synchronous function but then the caller needs to use a way to say okay i will wait or i will mark this to to be a weight and i will leave to the system to do the rest by the way this function is marking that we need to use try so let's use try and now the problem here is that if we have a throwable function we need to mark this function to be trouble too and for that it's really simple it's just using throws a sink would be before throws but before the arrow that reflects the return type in this case it's not a return there's no return type but just for you we can mark this as void just to get the complete syntax here okay that's it and you may guess hey where is the error value there's no error value i mean yeah it's implicit because since that this function is throwing an error yeah we will propagate that error automatically so the color of this function will have to take care of that not this function amazing if everything is fine we are getting data automatically so if we got any error this function will throw an error and that's it so everything after this line 84 will be ready to go so this is amazing also if you want to validate something about the url response we can do that so let's do it as you can see here we are checking if this response contains an status 200 and if it's the case we will continue otherwise we are drawing an error right away to say that we got a server error for any reason amazing now let's decode our data really quick finally here we are ready to go the only thing we need to use is you know maybe handling the scenarios that our completion handler did before and that's it let's go back for a moment what we did here first we got the url and then we use an asynchronous function in this case we are using url session that contains a data function that is a synchronous and it's capable to read the url the information from that url then return information in this case we got data and response if everything's okay otherwise this try action will then produce an error and then we won't continue with the rest of code and anything that is calling this async load will then propagate an error but what is happening here and it's interesting it is a weight a weight is telling swift that this function will be suspended for a short period of time what suspension is doing here is just giving the control to the system about the process of this operation so in other words at this point we are telling the system okay take care of this function and once we got something go back to the point that means we will wait until receiving anything and if everything is fine we will continue with execution of this line and so on also the good thing is that we are freeing the thread to do other things we are not blocking threads here which is amazing and also the color of this function needs to mark this as a weight because this function is asynchronous and in this way you generate a tree of asynchronous operation the system is free to do other action while it's getting the response of what is happening here now let's call this a sync load in or load method we need to just call a sync load but again we need to mark this method load to be asynchronous too and mark this as try because yeah we are propagating an error we need to use a weight to market this as a synchronous function that is wearable okay now we need to handle the error so let's do a do catch action let's run this oh we got something yeah we need to inform swift here that yeah this function requires a weight and it's working as you can see we are getting the pokemons here and our pull to refresh action it's working it's amazing now a couple of things here if you're marking a function to be a sync this is not automatically be suspendable by the system is the system which will decide if this function requires to be suspended or not you are just marking that yeah this function is prepared to be asynchronous and it's prepared to be suspendable but it's not mandatory to do that by the system at the same time if you're marking this to be a weight there's no guarantee that this function requires to be suspendable it's just important for you to understand that look at that this code is like a synchronous code right it's like a normal code that you use there's no any closure here that we need to care or something you just need to handle this situation and if everything is fine then you continue here otherwise you got an error and here with this just simple word you are telling swift that yeah this function is prepared to be suspended at some point and the system will take care of that there's no requirement to do to use external dependencies or anything else compare that with this it's so annoying how much thing we had to use in the past without any external dependency handling this situation my eyes my ocd is ah so happy pretty short lines to get the same result also you don't have to use this thing at all now before ending i would like just to point out something because i saw some messages on twitter saying that yeah it's the end of combine blah blah blah i would like to say no i mean combine yeah you can get the same result that we are using with a sink or with clotures using combine and yeah there is a functional way that we are using here but combined it's also for you to create streams of data from a publisher to a subscriber and actually you can create a synchronous calls with combine yeah you can you create your own extensions to make for example on a sync map or something i will leave you in the description one great article from john sondell that talk more about that so but in other words yeah you can use combine and asynchronous functions together they are not fighting each other you have now more tools for your development since ios 15 of course so tell me what do you think do you think this is so revolutionary for swift i would like to know your thoughts about that in the comments below don't forget to subscribe and tell me which video we like to see next i am really happy to read your comments and explore more with you in details other things don't forget to follow me on twitter because it's the fastest way to communicate and see what video or other things are coming for suffer tips thank you so much and have a great day
Info
Channel: Swift and Tips
Views: 2,322
Rating: undefined out of 5
Keywords: swift and tips, swift && tips, swiftandtips, pitt500, Pitt, Pedro Rojas, Swift, SwiftUI, ios, ios development, swiftlang, iosdev, WWDC21, WWDC, Task, Refreshable, SwiftUI 3.0, iOS 15, SwiftUI 3, swiftui, async, await, async/await, suspension, asynchronous functions, asynchronous, closures, Swift 5.5
Id: esmf26aGz4s
Channel Id: undefined
Length: 19min 59sec (1199 seconds)
Published: Mon Jun 28 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.