This section covers various approaches to composition of suspending functions.

    Assume that we have two suspending functions defined elsewhere that do something useful like some kind of remote service call or computation. We just pretend they are useful, but actually each one just delays for a second for the purpose of this example:

    What do we do if we need them to be invoked sequentially — first and then doSomethingUsefulTwo, and compute the sum of their results? In practice we do this if we use the result of the first function to make a decision on whether we need to invoke the second one or to decide on how to invoke it.

    We use a normal sequential invocation, because the code in the coroutine, just like in the regular code, is sequential by default. The following example demonstrates it by measuring the total time it takes to execute both suspending functions:

    1. import kotlinx.coroutines.*
    2. import kotlin.system.*
    3. fun main() = runBlocking<Unit> {
    4. //sampleStart
    5. val time = measureTimeMillis {
    6. val one = doSomethingUsefulOne()
    7. val two = doSomethingUsefulTwo()
    8. println("The answer is ${one + two}")
    9. }
    10. println("Completed in $time ms")
    11. //sampleEnd
    12. }
    13. suspend fun doSomethingUsefulOne(): Int {
    14. delay(1000L) // pretend we are doing something useful here
    15. return 13
    16. }
    17. suspend fun doSomethingUsefulTwo(): Int {
    18. delay(1000L) // pretend we are doing something useful here, too
    19. return 29
    20. }

    It produces something like this:

    1. The answer is 42
    2. Completed in 2017 ms

    What if there are no dependencies between invocations of doSomethingUsefulOne and doSomethingUsefulTwo and we want to get the answer faster, by doing both concurrently? This is where comes to help.

    Conceptually, async is just like . It starts a separate coroutine which is a light-weight thread that works concurrently with all the other coroutines. The difference is that launch returns a Job and does not carry any resulting value, while async returns a — a light-weight non-blocking future that represents a promise to provide a result later. You can use .await() on a deferred value to get its eventual result, but Deferred is also a Job, so you can cancel it if needed.

    1. import kotlinx.coroutines.*
    2. import kotlin.system.*
    3. fun main() = runBlocking<Unit> {
    4. //sampleStart
    5. val time = measureTimeMillis {
    6. val one = async { doSomethingUsefulOne() }
    7. println("The answer is ${one.await() + two.await()}")
    8. }
    9. println("Completed in $time ms")
    10. //sampleEnd
    11. }
    12. suspend fun doSomethingUsefulOne(): Int {
    13. delay(1000L) // pretend we are doing something useful here
    14. }
    15. suspend fun doSomethingUsefulTwo(): Int {
    16. delay(1000L) // pretend we are doing something useful here, too
    17. return 29
    18. }

    You can get the full code here.

    This is twice as fast, because the two coroutines execute concurrently. Note that concurrency with coroutines is always explicit.

    Optionally, can be made lazy by setting its start parameter to CoroutineStart.LAZY. In this mode it only starts the coroutine when its result is required by , or if its Job‘s start function is invoked. Run the following example:

    1. import kotlinx.coroutines.*
    2. import kotlin.system.*
    3. fun main() = runBlocking<Unit> {
    4. //sampleStart
    5. val time = measureTimeMillis {
    6. val one = async(start = CoroutineStart.LAZY) { doSomethingUsefulOne() }
    7. val two = async(start = CoroutineStart.LAZY) { doSomethingUsefulTwo() }
    8. // some computation
    9. one.start() // start the first one
    10. two.start() // start the second one
    11. println("The answer is ${one.await() + two.await()}")
    12. }
    13. println("Completed in $time ms")
    14. //sampleEnd
    15. }
    16. suspend fun doSomethingUsefulOne(): Int {
    17. delay(1000L) // pretend we are doing something useful here
    18. return 13
    19. }
    20. suspend fun doSomethingUsefulTwo(): Int {
    21. delay(1000L) // pretend we are doing something useful here, too
    22. return 29
    23. }

    It produces something like this:

    1. The answer is 42
    2. Completed in 1017 ms

    So, here the two coroutines are defined but not executed as in the previous example, but the control is given to the programmer on when exactly to start the execution by calling . We first start one, then start two, and then await for the individual coroutines to finish.

    Note that if we just call await in println without first calling on individual coroutines, this will lead to sequential behavior, since await starts the coroutine execution and waits for its finish, which is not the intended use-case for laziness. The use-case for async(start = CoroutineStart.LAZY) is a replacement for the standard lazy function in cases when computation of the value involves suspending functions.

    We can define async-style functions that invoke doSomethingUsefulOne and doSomethingUsefulTwo asynchronously using the coroutine builder with an explicit GlobalScope reference. We name such functions with the “…Async” suffix to highlight the fact that they only start asynchronous computation and one needs to use the resulting deferred value to get the result.

    1. fun somethingUsefulOneAsync() = GlobalScope.async {
    2. doSomethingUsefulOne()
    3. }
    4. // The result type of somethingUsefulTwoAsync is Deferred<Int>
    5. doSomethingUsefulTwo()
    6. }

    Note that these xxxAsync functions are not suspending functions. They can be used from anywhere. However, their use always implies asynchronous (here meaning concurrent) execution of their action with the invoking code.

    The following example shows their use outside of coroutine:

    This programming style with async functions is provided here only for illustration, because it is a popular style in other programming languages. Using this style with Kotlin coroutines is strongly discouraged for the reasons explained below.

    Consider what happens if between the val one = somethingUsefulOneAsync() line and one.await() expression there is some logic error in the code and the program throws an exception and the operation that was being performed by the program aborts. Normally, a global error-handler could catch this exception, log and report the error for developers, but the program could otherwise continue doing other operations. But here we have somethingUsefulOneAsync still running in the background, even though the operation that initiated it was aborted. This problem does not happen with structured concurrency, as shown in the section below.

    Let us take the example and extract a function that concurrently performs doSomethingUsefulOne and doSomethingUsefulTwo and returns the sum of their results. Because the async coroutine builder is defined as an extension on , we need to have it in the scope and that is what the coroutineScope function provides:

    1. suspend fun concurrentSum(): Int = coroutineScope {
    2. val one = async { doSomethingUsefulOne() }
    3. val two = async { doSomethingUsefulTwo() }
    4. one.await() + two.await()
    5. }

    This way, if something goes wrong inside the code of the concurrentSum function and it throws an exception, all the coroutines that were launched in its scope will be cancelled.

    1. import kotlinx.coroutines.*
    2. import kotlin.system.*
    3. fun main() = runBlocking<Unit> {
    4. //sampleStart
    5. val time = measureTimeMillis {
    6. println("The answer is ${concurrentSum()}")
    7. }
    8. println("Completed in $time ms")
    9. //sampleEnd
    10. }
    11. suspend fun concurrentSum(): Int = coroutineScope {
    12. val one = async { doSomethingUsefulOne() }
    13. val two = async { doSomethingUsefulTwo() }
    14. one.await() + two.await()
    15. }
    16. suspend fun doSomethingUsefulOne(): Int {
    17. delay(1000L) // pretend we are doing something useful here
    18. return 13
    19. }
    20. suspend fun doSomethingUsefulTwo(): Int {
    21. delay(1000L) // pretend we are doing something useful here, too
    22. return 29
    23. }

    We still have concurrent execution of both operations, as evident from the output of the above main function:

    1. The answer is 42
    2. Completed in 1017 ms

    Cancellation is always propagated through coroutines hierarchy:

    You can get the full code .

    Note how both the first async and the awaiting parent are cancelled on failure of one of the children (namely, two):

    1. Second child throws an exception
    2. Computation failed with ArithmeticException