Kotlin Coroutines tutorial for Beginners - Understand Kotlin Coroutines on Android with example

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello welcome back to my channel today our topic is cocaine co-routine in Android coltan is basically another option to work on trade coroutine manages backgrounders to handle long-running tests elegantly and efficiently by the way this tutorial is completely beginner friendly if you have no idea what co-routine is or you don't know anything about background trading on android then this tutorial is for you I will show you the basics of Kotlin core routine throughout a very simple app where you would learn how to use a routine in your Android projects this tutorial consists of coding and theories on co-routines before explaining the core routine I would like to give a short brief on trading mobile devices have possessors to possess our data now it is most of the mobile devices have multiple processors and each processor runs concurrently this is called multi processing on top of that operating system imposes more than one threats to come execute tasks this is called multi-threading now in Android a foreground thread name main thread is responsible to all related stuffs all the UI related things like creating a new UI or changing text of a textview happens on the main thread that's why it is sometimes called a UI thread this is this main or UI thread also is the default rate which means unless you create a new other create any other trade by yourself all those tasks will have executed in the main thread this brings a potential challenge now if it tasks like fetching data from the web or accessing internal SQL DB or a school SQLite database which are long-running task list if this task appears and if you block the main thread for too long your app may freeze may showing application not responding dialog and eventually gate crash which will the bad user experience cortland co-routines performs long-running test away from the main trade without blocking the main threat with the help of coroutine we we can perform long running tasks in a background third grade the result from get the result from the death trade send it to main trade and thus make our core non-blocking so enough talk let's jump into the code and see what problems we are going to solve today using quarterly in core routine I have created a fresh new Android studio project in my Android studio and if I go to the activity main.xml and here we found we can find one just one okay give it a one button and one text box so I give it a little margin here okay now we we are not doing much in our in this project because it is all about quality and app is very simple it contains only one one button and a text field now going back to our main activity and first we will simulate a normal running test and what a long-running task would look like but before we creating any longer it does we need to add dependencies for core routine on to Gradle windowed curdle and need to add these three lines by the way I have put the dependencies in the video description please you copy paste copy those dependencies in your project if you want now we give a sink now opening our main activity and here we will simulate a long-running task so we name it a create a function name on long running tasks and say this function from this function we will update our we will update this text view okay so we'll just set it and it takes result or text we will simply put it and I mean it that what should she say response response okay now this thing will work fine without any problem because but if we put a delay or traitorously in this case we can say that trade dog sleep and we sleep it for 2,000 milliseconds that is to second and when this function will be called this this fast this other the first line will be executed this state or sleep that means our function will wait for to second and or 2,000 millisecond and then place this line so we are considering to two second as a long-running task okay so we will call it from that so button on clicked or sit on click listener and be long-running task okay and we're on our put it in your emulator we see a button and when we press the button it's freezing and after two seconds it is showing the response so when I once trace this the total scene is freezing it is not working anymore okay let me let me change the little so we can you can understand it more clearly so it will be it will be something like text and we will create a new line so it's response for his response we will create a new line so it's like the previous thing the text is on dot X dot twist stream sorry to string and we'll create a new line and the response line okay response text now running a budget again and opening our singlet or emulator and when it plays the week wait for two seconds the whole UI is freezing for the two second and click and another response is adding as new line so the thing is that it's a long-running task it's wait for two second and when I take the whole entire main entire activity is freezing you see it's not working anymore okay when I place it is freezing and after two second it's responding okay so this is a this is definitely an issue and we are going to resolve we will use code Licata line quality to do the long-running task in the background thread and take the result in the center result to the main trait and show it in the main now at this point you may thinking that co-routine and trade are same but in reality they are not same although co-routine works like trade but co-routine is not trade thread is mainly managed by the operating system itself and core routing is managed by a user in space level by Kotlin runtime when a core routine is created that core routine is assigned to a thread it remains to the thread until the Guru team gets suspended I will discuss about suspending guru team in some minutes but for time being assume that coroutine remains to that said until the core routine gets suspended after the suspending the same core routine can resume to another trait the score routine doesn't belong to a particular trait also consider a core routine has some jobs to do a guru team may have multiple jobs to do and a thread may contain multiple core routine let's get a get back to code and see how to create quality from our code we got to know that long-running task is a long-running task function and eat lace to see okay it lays the function to wait for two seconds because of thread or sleep but we won't use thread or sleep anymore because it is a notorious thing like if a so what does the three-toed sleep for two seconds do so when we write this state or sleep and give it a time so the interface is blocked and the interest takes time for two seconds which is not accepted because we may have some co-routines may have fifty or hundred coroutines so when we write that that this kind of thread or sleep it will make the whole thread locking okay instead of this thing we can write a routine style that delay for two seconds what does it do this simply so we haven't created any core routine yet but for time being we assume that this delay only billions to this core routine number one so writing this delay for two millisecond to second actually hold this it has no effect on co-routine - or any other coroutine on in the trail so all other coroutines will work fine only delay that goroutine okay now it is showing an error when we write the delay it is showing an error that and seeing the suspend function delay should be called only from a goroutine or another suspend function so now Android compiler is saying that we need to if we use the delay we need to make the function a suspect so we make this function and suspend but creating this making this function suspend will make the same erode here so what does the suspendu before before fixing this issue we will see what does the suspend do in the co-routine let's see what happens when a coroutine gets suspended a goroutine can be either running or suspended let's assume we have three cou routines running in a thread co-routine number two is a long-running task we suspend this core routine here suspend means instead of waiting for the court to execute that core routine our function transferred to another trade by Courtland runtime a suspend co-routine is not associated to any particular thread it can resume to another thread and may result back to previous thread coming back to our code I am forgetting to delete the line to remove the line I just remove the line I do not need to eat or sleep any more and we will create a core routine to get rid of this error so we will create a routine but first we will create a scope for the core routine whether the guru teen is in main or i/o so while scope and it will be get a quote in a scope I will explain everything in a little while so don't worry routine scope and it will be dispatcher dispatchers dropped aisle and okay so what is what does this line do actually we want to run this long running tests no more in our main trade which we want to do it in our in any other background check for this we have goo routine or forces three kind three kind four kinds of mainly four kinds of state one is I own a you is basically used for input/output operation or network related calling or SQLite database operations so this earth is for i/o and maim is used for updating the UI and default is for default is for any long-running task or any background treat and unconfined is will not use this this type of dispatcher so basically we will use dot IO because we want to separate we want to run this long-running task function to a separate thread so choose IO so what does it do what does this line to this line will create a thread a core routine inside the trade so like this this line you'll create a co-routine inside the thread and this thread this core routine but or thread is IO related so this will do simply now we will create go routine so we'll create the routine use the scope dot launch so launch is the Builder for the core routing function and yeah inside the launch function we will create the long-running task okay we will also remove the line from here because the slower long-running task is a fast band function and it is inside the IO co-routine scope so and we know that all the you a related thing we only happen in me so we simply remove this line listed the we will create a log here dr. T and and we will wash away say we will create a tag here that the tag name may be the trade name so the trade will be great without current rate we want to show the name of the current trade and it will be there's a properties name name and we simply put it like response okay not you response and if we run over app with this app this long-running task will send back to ayat rate let's see we run that we open our emulator and see the click button and when I press the button ok it's not showing anything but it's showing the inside the locket that default dispatcher worker and response will filter it as response but one thing is happening that it's not freezing the UI the ey is not blocked you may see that I can click here I can click here I can click click Li and after 2 seconds every 2 seconds the response is showing in locket but our if you can remember that at first when we check when I click this button this whole UI freezes for was freezing for 2 seconds we didn't we cannot do anything in the UI so definitely this is a improvement and that our long-running task is running and thread and this is the trade name sometimes the default dispatcher worker 2 sometimes it goes to 3 because as we have said that when they found core routine or suspend function is has got suspended it doesn't belong to any particular thread it can work on any thread and the trait tag we have different is IO ok that thing is done the our long-running test is running on the background thread now we want to we want to get the result back into our into our UI but we already have know that UI data can be on can only be updated and related things can be done only in main thread instead of background kit so we create a function and this will be okay create a function name suspend this function will be a suspend sustain function and will be rained UI data and this will take a message string type so string and we can we can launch we can create we can launch we can create a scope and launch but we have another built-in function for creating new idea of creating go routines that is with context so what is the difference between whip context and launch those are basically same but with context we are using it with context because we we want to we want to change our routine from you I am from this IO this yoga routine is a routine scope to another coroutine and that guru thing is in main so our transition from I owed to mean we are changing the context so we are writing that with context function so with context it will be dispatchers dot mean as we are we want to show the data in me go routine so it will be me and inside it we will show the data so it will be text result dot okay first we will call the call the function so it will be print UI data from the long-running task and we will send any any any kind of response or any any sting so it will be in our case it will be response you'll write response okay you can choose anything so this result dot text and we will take the first we will create a new line so this dot twist ring create a new line and bring the message so okay okay let me run this app okay so I click here and after two seconds the response text is appearing appears and when I click continue click click click click click the you is not blocked and the response is coming after two seconds sequentially and we can say that our we have successfully applied co-routine into our project so in a nutshell if I recap everything that we have a long-running task which is which takes almost 2 minutes 2 seconds to complete the task as and as it is a long-running task we have we have shifted our this long-running operation to a ioco routine and inside the i/o core routine when the result is ready we call another core routine from our this suspend function and we go to the or this a certain function and here we create another core routine with which runs in the main trade and which simply show our data from IO co-routine - main routine so this is our take out from the course this video tutorial is that we have learned a basic very basic of core routine I have a plan to release two more videos on co-routine one is core routine job and another is go routine as Ingrid Lee so if you want to see this videos please subscribe if you haven't subscribe and if you like the video smash that like button and if you have any question or any solution please let me know in the comment box so that's it thank you for watching this tutorial see you in the next tutorial thank you
Info
Channel: Munir Hoque
Views: 3,692
Rating: 4.8518519 out of 5
Keywords: Kotlin Coroutines, Kotlin Coroutines Explained, Android Coroutines, Kotlin Coroutines Example, Kotlin Coroutines Tutorial, Android Coroutines Example, Android Coroutines Tutorial, Kotlin Coroutines tutorial for Beginner, Easy way to understand kotlin coroutines, Understand Kotlin Coroutines on Android, Suspend function example, Coroutines withContext example, munir hoque
Id: rJ-cfoFCDAI
Channel Id: undefined
Length: 24min 8sec (1448 seconds)
Published: Mon Feb 24 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.