In this video, learn how to start a coroutine by getting access to the Job value that’s returned from the launch method. Also, see the use of two coroutines in the same function and how they run in parallel.
- [Instructor] We can easily start a coroutine that doesn't block the main thread. But what about another coroutine? Do they block each other from getting work done? Well, no, they don't have to. Let's implement this startWithLaunchMultiple method. We're first going to duplicate the code that we have here inside of the previous test. And let's paste it, and starting on line 38, and then we're just going to copy the code for our launch coroutine. And we're going to duplicate that right underneath, and then let's change what gets printed.
The first one, on line 42, we're going to change it to Inside1, and then here, on line 47, we're going to change it to Inside2. Now let's go ahead and run this test. So if we look at our results, we get starting, and then inside 1, and inside 2. And then finally, stopping. This helps us to see that both coroutines were able to run successfully under that second and a half that we let our main thread sleep.
This is because coroutines allow you to process requests in parallel. Now this will certainly come in handy inside of our Android applications. So let's move on to our next example. This time, we're going to update our launch function to take in a value for the start parameter. So let's go ahead, close this window down, and we're going to move on to our startWithLaunchLazy function. Let's go ahead and copy our code from the previous function just to make it easier on ourselves, and then we'll come down here to line 57 and paste.
Now the only thing we're going to change is on line 59, for our launch function. We're going to add the coroutine start lazy value. Now, let's run it. Notice this time, we only get starting and stopping. That's because we stated that we wanted to launch our coroutine lazily. So how can we start it now? Let's close this window down, and what we're going to do is get access to the job value that's returned from the launch method.
So right here on line 60, we're going to create a variable to store the result of the launch call which is job and then right underneath its definition, down here on line 65, we're going to make a call to job.start. And we'll leave everything else the same. Let's go ahead and run this test again. And you'll see that indeed, we do get starting, inside, and stopping. Using coroutines in this way is very useful if you need to have more control over your coroutine's execution.
- What Kotlin has to offer
- Working with lambdas
- Common Android extension functions
- Kotlin Android Extensions overview
- Making use of the Anko library
- Working with coroutines
- Nullability and collections