Kotlin Coroutines Beginner Example (Android)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
alright so in this video I'm gonna show you the simplest possible beginner example so that you can get started with co-routines and use them in your android projects I know that they're a very new thing so a lot of people don't know what they're about how to use them anything like that so this is gonna focus on beginner beginner beginner complete beginners you know absolutely nothing and I'm gonna show you how to get started in and actually show you a practical example of how you can use co-routines so typically like when you're using co-routines you need to do work on a background thread that's what it's all about that's what arcs Java does that's what executor x' do async task although you shouldn't use async task it sucks but Co routines are essentially the same thing it's another option for threading on Android so so the kind of the most practical common use case for one you need to use a background thread is number one if you're making a request to the network so using something like retrofit or volley you need to do that on a background thread because you don't want to block the main thread the second probably most common is accessing the internal SQLite database on the phone so that means using the room persistence library or if you use the old-fashioned way which I don't recommend doing with the old SQL database builder thing or open helper don't use that used room persistence library but anyway those are the two kind of most common cases when you're gonna need to use background threads on android network requests and internal requests to the database on the phone so what we're going to be doing in this example I'm going to show you a very simple beginner example we're going to kind of use a KO routine to simulate a network request or a room request something that would block the main thread we're gonna get a result and then we're gonna take that result and send it to the main thread where it can be displayed so getting a results from a background thread and then taking that result and and displaying it on the main thread very practical you're gonna see a very simple example so you can get started with co-routines let's get started one more thing before we start I wanted to mention that I'm gonna be showing you how to solve another very common problem that comes up in Android development and co-routines make it very simple to handle imagine the scenario when you need to make a request to network or two-room persistence library whatever you need to make a request you need to get a result for that request then once you have that result you need to make another request and maybe another one it's it's this sequential nature of making requests you need a result once you have that result you need to make another request using that result once you have that result you need to make another request using that result and so on and so on doing this with typical methods like rx Java live data executor z-- this is very tricky you have to have lots of callbacks it's often it gets messy basically there's not like an ideal way to do it with co-routines it's so simple it is so so simple I absolutely love it it's so simple I'm gonna be showing you that in this video also so make sure to keep watching to the end because that's gonna be the the best part let's get started now alright so co-routines for beginners step number one getting the dependencies this of course is the first step you need the co-routines dependency you can get it from I got it from the code lab you can just like google android co-routines code lab see what I just googled there that'll be one of the first links that comes up you can look at the code on github or you can go to the actual code lab go to step number two getting snow step number three and that'll give you the dependencies down there or just go to the source code that I have for this project there's a link in the description of this video and you can copy the dependencies there either way get the dependencies and get them into your project by the way I didn't show you like creating this project but it's just a blank activity there's a single activity a single layout I'm using Kotlin and I'm using Android X nothing fancy here just to show you just because this is a beginner example all I did was go empty activity use Android X and use Kotlin that's all I did to create this project so anyway now the next step is I want to show you what's going on in the activity so I was just some very basic stuff in our activity I have a button and a text view the textview is going to display some text as you might have guessed and the button is for firing off that simulated Network request that we're going to be doing some background work on so you can just copy this it's very simple a button and a textview very straightforward that's pretty much all the prerequisites you need to get started now let's go into main activity and let's let's take a look at simulating this background request and using co-routines to do so so the first step here is going to be building a method that returned something asynchronously so you can imagine a network request or something to the room persistence library so let's build that so the first method will be private suspend this is a this is one a calling keyword or Kotlin co-routine keyword suspend which I'm going to explain in just a second here and I'm gonna call this function get resolved one from API and you you're probably gonna you're probably guessing right now why did I name it result one because we're gonna have a result too later on so get result one from API is our first function and so what does this suspend keyword well suspend will in when you're dealing with co-routines will mark this function as something that can be asynchronous so it doesn't necessarily mean that it's gonna be on a background thread or on the main thread it just means that it's going to be able to be used in a KO routine and just to kind of give you an example I'm gonna pull up another project that I've been working on so here is a Dao class for the room persistence library notice all of these methods are suspend functions if I remove this they can't be used in co-routines so if they have suspend the suspend keyword it means that they can be called from within a KO routine and the same goes to retrofit retrofit requests are identical you just mark them with the suspend keyword and then they can be called in a covert eeen and therefore executed on a background thread alright so now let's let's build this method so first I actually want to I want to log the thread that this gets called on so I'm gonna write one more method private font fun log thread this is gonna be the method name and it's gonna be a string and I just want to print line and debug just to give me something to filter on I'm gonna print the method name and then the thread so : I'm gonna do dollar sign and in here do thread Kern thread name so you can see what what methods being called and what covert inor thread it's being executed on and actually before I carry on because I've used a couple kind of confusing statements in the last minute here I need to clear this up before we move forward so you you might be a little confused about what I just said there I used I kind of used the word co-routine and thread interchangeably but actually co-routines are not threats there are like threads but they are not threats I think the best way to think of them is like if you think of a Co routine as a job that needs to be done and the thread as the place where the jobs get done but keep in mind that any number of co-routines many Co routines can be operating at the same time inside a single thread so it's it's not a thread many Co routines can exist inside of a thread and be executing whereas there can only be one thread to host all of those co-routines well technically you could have more threads but it would be like a totally different category so you can have any any number of co-routines doing some work inside a single thread and they can be executing all at the same time so just kind of keep that in mind as we move forward all right so let's go into our get result method here and we're going to log the thread that we're working on and I'm gonna pass the method name right here so there's the method name getting passed to our method and that's going to print out what co-routine and what thread is currently the work is being done on next I'm going to write a function called delay this is a co-routines thing now you might be thinking oh this looks kind of similar to thread thread sleep which is how you probably always did it in the past but these two are very different things as I just mentioned co-routines are different than threads they aren't threads there can be many co-routines operating within a single thread so that's what this delay will do this delay will only delay this single co-routine it will not delay the thread itself but by calling thread sleep you will sleep the entire thread if there's many co-routines working in that thread all of them will go to sleep so there's a big difference here this is like delaying a single co-routine this it will not interfere with any of the other Coe routines that are operating on that thread whereas thread dots sleep will sleep the entire thread and all the Coe routines inside will be disabled basically you never want to call thread dot sleep inside of a co-routine now that we so now that we want to this is going to be simulating the delay for making the request to either room or the network we're just delaying it for one second and then we're going to return a result and this is going to be result number one actually I could make this into a constant and I need to actually return a string from this so let's go up to the top here and just do private now we'll do a result one and that's can equal result result one and pass this right here okay so now how do we execute this suspend function and get a result well right away you might be thinking well I'll just you know do value or result one actually I'll make a method for it so let's let's make a let's make one more method we'll do private function fake API request is what we'll call the method and the inside here I'll do Val result equals Orgel result 1 equals get results from API and then I'm going to come back up into this button click and I'm gonna call fake API request so what's happening here it's giving me a warning it says a suspend function get result one from API should be called only from eiko routine or another suspend function so it's it's basically telling me that I'm missing a step I'm trying to call this asynchronous co-routine function it's marked by this suspend keyword inside something that is not marked with the suspend keyword and it's also not inside of a co-routine so there's a few ways you can fix this you probably already thought of this add suspend to this method but then you basically just propagate the error back up to this method and you have the same issue so what we have to do is we have to launch a KO routine because right now we have no co-routines we just have a suspend function so we need to actually do that and and launch our first KO routine so i'm going to come up into the button click here and we're going to do that oh and we can mark this as suspend so America says suspend function the error is going to go up here and now we are gonna launch a KO routine inside of this button click now there's a couple ways you can do this with co-routines there's this thing called scoping this kind of property called scope and co-routine scopes and what a co-routine scope is is a way to organize co-routines into groupings as I said before co-routines are like jobs so a co-routine scope or a co-routine context is like grouping a bunch of jobs together so if you had to execute job one through five so job one two three four five and suddenly it failed on like job three you would cancel all of the co-routines within that scope and they would all cancel so it's a way to it's a way to group them together so that if one fails then you can cancel them all if you know result changes you can you can do things you have options and I'll actually pull up the co-routine documentation and we can read what they say about co-routine scopes so it says it defines a scope for new Co routines every Co routine builder is an extension on curtain scope and inherits its co-routine context to automatically propagate both context elements and cancellation so it's it's a weighted yeah to group jobs together or Co routines into a similar categories so that you can take action on many of them at once that's that's kind of how I like to think of them so let's uh let's stop talking because you could probably talk about Karine scopes for a long time and look at a lot of different examples so I'm trying to keep this simple so that you can see something in action that you can use right away so the first kind of scope probably the most common scope that you'll end up using is co-routine kuru teen scope and here inside of this bracket you want to specify the kuru teen context the two options that you'll find yourself using are either il so just the letters IO if I import that that means input output so that's like gonna be your network requests or your request to a local database there's main which as you might guess is for doing work on the main thread and there is which what is it there's the last one default so default is for doing any heavy computation work so the three the three types I'll just type them up here is IO main and default those are the three kind of co-routine scopes that you'll find yourself using all the time and IO is for network and local database interactions things like that main is obviously for doing stuff on the main thread so interacting with the UI and then default they say to use for heavy computational work so like you have to filter a large list and pick things out and arrange at different ways that's when you want to use default so we are simulating a network request with this with this video with this example so I'm going to be using the IO option the next step is calling dot launch on this co-routine context what this is this is a co-routine builder so this is essentially what constructs the co-routine and gets it all ready to go so now all I need to do is just move this method inside of my Co routine and I'm ready to go this is it tells it what context I want to launch my cover teen in and then I'm calling dot launch to actually create that curl routine and start it up so that's it so now this will this will get called let's let's print this let's go print line I'll go debug and just get that result number one and we can run this and take a look so let's do I'm pressing shift f10 which is the hotkey to run it on my computer and I'm going to choose a device and run it alright so that we have the app I'm going to bring up the logcat just so we can see what's going on here looks like I got a bunch of a bunch of old stuff in there I'm gonna click it it says right there get results from API there's that thread printing out so that's the that's the logging thread method printing out there and then it says debug and result number one it present prints result number one so everything is working as we expect so now that we've got a result from our fake API request what if we wanted to set this result to the textview in activity main so if you look at activity main there's a button and a textview so suppose i wanted to take this result and now set it to a textview now you might be tempted to just do text which is the ID of that textview do set text and do result number one but if you have been around Android development for any amount of time you will probably know that yes that will cause your app to crash it's gonna cause you out to crash because we are doing work on a background thread with our fake API request method and we're trying to interact with the UI by setting that so I'll just run it and just show you that it does actually crash when I try to do that so if I click the button it's going to get the result and it's gonna crash so how can we solve this problem well we need a way to basically send this results to the main thread where it can then be set to the the textview so I'm gonna create a method private fun set new text I'll call it it'll take input as a string and I will do value new text equals text text dot to string so I'm getting whatever current text is already on the textview and then I'm appending the new text so new line and I'm going to append the input so dollar sign input so that will take to get the text it's already in the textview get the new input a pendant and then we're going to set it so text dot text equals new text there we go so that will set the new text but still that's not doing it on the main thread that's just gonna do it on whatever thread it gets called from so that's still gonna crap crash the app that doesn't solve our problem so I'm gonna create one more function it's gonna be a suspend function it's going to be called set text on main thread it's going to take a string as input and now we want to we want to fire up a new KO routine that will do its work on the main thread instead of doing it on IO or default so basically we want to make use of this main kind of this co-routine scope up here so inside here you can do this a couple ways you can do it the way that we did before by doing co-routine scope and then you know passing main in here or you can just write with context pass main and then that's it with context main and that will that will fire up a co-routine and get it started for you so all I need to do is do set new text and then pass that input and everything will get set correctly so now let's try to call set text on main thread inside of here so set text on the main thread and pass result 1 and let's see if that gets added to our UI and the app doesn't crash so I'm pressing shift f10 to run it which is a shortcut on my computer and running the app all right there's our application let's click it wait one second and there is result number 1 getting printed 2 that textview so everything's working we're not freezing the UI you can see I can keep clicking this we keep getting results everything's working as intended so this is a very simple example but this is like you do this all the time in Android development you go and make a request to a network or the rim persistence library you get a result and you display that result so this this pattern is gonna come up a lot even though it seems very simple but that's the point I mean coroutines make this very simple to do and that you're just barely scratching the surface with what they are able to do like this is a very simple example and I plan on making more videos with more more more examples and showing you what they really can do the other things that they can do now I'm sure you're wondering what is this with context things I didn't really explain that I just kind of used it and showed you that it was able to switch the context of the co-routine and we were able to do that work on the main thread or set the text on the main thread if you call with context within a Cober team it will switch the context of the kuroh team to whatever you mentioned so this is another property of co-routines they're they're their thread independent I guess I could say you could start a co-routine in one thread pass it to another thread to do some other work pass it to another thread to do some other work it doesn't matter you could the co routine can be started in one thread do its work in another thread do some more work in another thread and then return to the main thread and all you have to do is change the context and there's other ways you can do this too with different method calls but the simplest way is to just call with context and it will take wherever that co-routine was doing its work and it will move it to the thread that you specify in this case it's main and then you able do whatever you like so that's that's another thing about co-routine it's another possible optimization you can make you can try to reuse covert eenz whenever possible and not keep firing up new ones so launch will build a new one and then you can just use with context to switch the context of that cover team and change where it's beaten where it's doing its work so that's yeah that's all I want to do for this example now we're gonna go into a little bit of a more complicated example are not really more complicated but I want to show you something else that's really cool that they can do and I mentioned this at the at the beginning of this video so a very very common thing you run into is you you want to make a request you want to get a result and then you want to use that result to make another request I'm going to show you how simple that is with co-routines so let's scroll down to the bottom and I'm going to create a second method here for getting a second result so private suspend function get result two from API and this is going to return a string again once again I want to log the thread I'm gonna pass the method name inside of here and we're doing almost the exact same thing this is gonna be another delay of one second and I want to return result result to this time and I'm going to create that property I thought I clicked create anyway well let's just copy this this is gonna be result two so let me result two and now we're going to retrieve that result after we get result number one so I'm coming into our fake API request method and after I set the text on the main thread for result number one I'm going to retrieve a result two so value result 2 equals get result from result two from API and I want to set text on the main thread pass result number two and that should be it so by default when you call suspend functions in this way within the same job they wait for completion so like result number one here it's gonna wait until it gets that result then it's going to continue it'll set the result it will get the second result and then it will set that on the main thread so now let's run that and see what that looks like open up the log get the app out here let's click it one second you get result number one the next second you get result number two so you can just imagine you know if for whatever reason you actually need it to pass you know results into here we'll say that this requires result number one and then you had to do something with it you could just take result number one pass it to the method and then make your request so by default that does this when the suspend functions are called within the same co-routine this one this one waits it'll continue do it Stewart stuff the next one will execute do it stuff and then get that result there's a lot of different ways you can do this like I said I'm just barely kind of scratching the surface on what co-routines can do I plan on making a bunch of new videos but hopefully this helped and you saw some cool examples of how you can make your first cover teen how you can you know fire it up in a on a background thread how you can then pass some work some some results to the main thread and display it so let me know if you like the video let me know if you want to see more because I could there's a little there's so much you can do with co-routines and I plan on using them in my newest upcoming project that I've been working on so let me know and thanks for watching you
Info
Channel: CodingWithMitch
Views: 120,973
Rating: 4.9659286 out of 5
Keywords: kotlin coroutines, kotlin coroutines android, kotlin coroutines android tutorial, kotlin coroutines android example, kotlin coroutines tutorial, kotlin coroutines tutorial android, coroutines kotlin, coroutines, coroutines android kotlin, understand kotlin coroutines on android, kotlin
Id: F63mhZk-1-Y
Channel Id: undefined
Length: 23min 12sec (1392 seconds)
Published: Tue Jul 30 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.