The Essence of Coroutines

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
co-routines are a fantastic part of cotlin and yet many cotlin developers struggle to describe exactly what co-routines are often we focus on what they do like async a weight and other background tasks so in this video we're going to put all of those things aside and we're going to focus on what the essence of Coe routines actually is we're going to distill them down to their core characteristics and by the end of this video you'll understand what makes a co- routine a co- routine so let's get started not with co- routines but with regular old functions and examine how execution typically flows between different functions now here I've got two functions in the main function we're milking a few cows and in the middle of all that we're going to call another function where we feed some chickens now any developer who's been writing code for more than a day or two can tell you what the execution path is going to be for this code we're going to milk two cows and when we get to this function call execution moves into the feed chickens function and after this function runs execution is going to return back to the main function here and we finish milking the cows and of course we can verify this by running the code which shows us exactly what we expect uh we're milking two cows feeding four chickens and then milking Two More Cows okay let's talk about this function call here when we call feed chickens now there are two sides to a function call First is the entry when the feed chickens function is invoked execution is going to pass from Maine into feed chickens and then there's the exit which is when the feed chickens function completes execution passes back from feed chickens into the main function again when feed chickens is invoked the state of the main function is still going to exist so even though the execution moves over to the feed chickens function this cow variable still exists and the main function is just kind of paused waiting for the feed chickens function to complete and once it does the variable will still have the same number in it now what about when the feed chicken function returns even though it's got this chicken variable once the function returns this variable is no longer going to exist in other words the state of this function is eliminated now I'm really just describing the properties of a call stack right when the main function starts we've got a stack frame with a cow variable and then when we call feed chickens we get another frame on that stack with the chicken variable and then once that's done that stack frame is popped off the off the top of the stack and its state vanishes so a function call pauses the function and preserves its state but a function return completes the function and eliminates its state now what if a function return could have similar properties to a function call so in other words what if a function could yield its execution back to its caller like a return would but also pause its execution and preserve its state as if it were making a function call and this is the essence of a co- routine the ability to pause its execution and preserve its state not just when calling another function but at any point so let's look at a very simple example of a co- routine here we're still milking cows and feeding chickens but instead of a regular function call to feed the chickens we're feeding chickens within a co- routine now I've created a few helper functions here uh like create co- routine yield and complete and I did this to keep the example here clean and in a moment I'll reveal exactly what these functions are all doing but for now I just want us to focus on the execution flow now in the previous code listing we milked two cows and then we fed all four chickens and then we came back and milked Two More Cows but in this code the execution is going to bounce back and forth between the two functions so that we'll milk a cow and then feed a chicken and then milk a cow and then feed a chicken and so on and you can see this from the output when we run this so again the big difference here is that this feed chickens is able to return execution back to its collar and pause its execution and preserve its state just like if it were making a function call but instead of calling another function it's returning the execution back to its caller now whereas our previous code fed all of the chickens in one go you can see this version interleaves the tasks of milking cows and feeding chickens code that runs like this is said to be concurrent because we're working on multiple tasks over a period of time now if you're like Mr Grumpy or calcr man you might be saying Dave why the first code's not concurent if it was also milking them cows and feeding them chickens well in our first code example with a regular function call we were also milking cows and feeding chickens so I guess you could say we were doing two tasks over a period of time but a diagram of that work would look like this where all of the chickens are fed at once in order to be considered concurrent we need to be able to bounce back and forth between the tasks doing a little bit of each task each time now like I've said earlier to keep the example clean I've omitted a small amount of implementation here but just to put all of my cards on the table let's see what I've been hiding from you we've got four functions here and the first is the create co- routine function and this one I created as just kind of a wrapper around an extension function with a similar name so let's use refactoring tools to inline this function call since create co- routine uninter expected is an extension function on a suspend function we're going to need to also make sure we add the suspend modifier before this block okay next this resume function is just a shortcut for resuming with a unit and we can easily inline that as well that just leaves two more yield and complete which are both shortcuts to a function named suspend Co routine when the Lambda that we pass to this fun function evaluates to this special co- routine suspended value then the co- routine is going to be paused otherwise we can just invoke resume inside this block to finish it out so here it is with no hidden implementation note that we haven't used async or launch or run blocking we haven't referenced any dispatchers we've not dealt with any jobs or deferred and in fact this project doesn't even depend on the cotlin x.c routines Library so we're calling some very low-level functions that we normally probably wouldn't call from our application code directly but by doing that we've gotten to see the essence of what co- routines actually is building upon this Foundation there are lots of ways we can apply co- routines including things like sequence generators D recursion um running code simultaneously async of weight and a whole lot more and between the standard library and the cin x. code routines Library we get all of those features but as we've seen the essence of co- routines is actually quite simple if you're looking for more information about co- routines chapter 20 of cotlin and Illustrated guide covers the most important Concepts that you need to know about co- routines in order to be effective with them day-to-day if you've purchased the lean Pub edition of the book then you've got early access to a draft of chapter 20 right now if you'd like to pick up the book you can get it at book. typ alascom or if you'd rather of course you can just wait until it lands in the online edition of the book which will probably happen sometime around the end of June also you should join hundreds of other cotland developers who have signed up for my new email newsletter where you can get the inside scoop about any new articles videos and other fun projects that I'm working on thanks so much for hanging out with me today and I will see you next time you've read the chapters online and now I'm proud to present the lean puff edition of cotland and Illustrated guy take the book offline with you mark it up in your favorite PDF software and get early access to new chapters as they're written you can pick up your copy today just go to book . typ aus.com [Music]
Info
Channel: Dave Leeds
Views: 6,215
Rating: undefined out of 5
Keywords:
Id: kIzjzjJGk0Y
Channel Id: undefined
Length: 8min 10sec (490 seconds)
Published: Wed May 29 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.