In this video, take a look at suspending functions and how you can take advantage of them. Convert the work contained in a suspending lambda to a separate suspending function.
- [Instructor] Let's take a look at suspending functions and how we can take advantage of them. We're here inside of the CoroutinesAsync class and we're going to add a new function in order to test suspending functions. Let's go ahead and copy what we have here inside of our previous function, usingAsyncTwice, and we'll just paste it at the bottom of the class file, and let's rename this one to usingAsyncWithSuspendFunction.
Then, instead of having two asynchronous coroutines nested inside, let's just pair this down to one. We'll delete what we have here in our second one, and let's go ahead and get rid of this summation and just change it to the result instead of the sum. Now, we're back to having just one inner coroutine. The next thing we want to do is extract out the code inside of our async lambda to a new function. Let's highlight the work that we have here inside of our async lambda from line 71 to 73, and we're just going to create a new function called ourWork.
It's going to return an integer, and then we'll paste that code that we have inside, and instead of simply just having the number 42, we'll say return 42. Now, notice that we receive an error here because we haven't specified ourWork as a suspending function. This is because we can only call suspending functions from another one or a suspending lambda. Let's go ahead and fix this by making ourWork function a suspending one, so we'll just add the suspend keyword, and then notice that that error went away there on line 85.
Now, to take advantage of this function, we're going to go ahead and replace what's here inside of our async coroutine, and we'll make a call to ourWork. What I want to point out is that inside of the gutter, you'll see the suspension points. This function can be suspended, as well as the call to await and then finally, the delay. Let's go ahead and add the test annotation to this so that we can run it and see our results. I'm going to come right here and run our rest.
Okay, and we get starting, inside first, our result of 42, and then stopping. So, all of the coroutines were executed properly, but this time, we were able to take advantage of a suspending function.
- 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