This section covers basic coroutine concepts.

    Run the following code:

    You will see the following result:

    1. World!

    Essentially, coroutines are light-weight threads. They are launched with launch coroutine builder in a context of some . Here we are launching a new coroutine in the GlobalScope, meaning that the lifetime of the new coroutine is limited only by the lifetime of the whole application.

    You can achieve the same result by replacing GlobalScope.launch { ... } with thread { ... }, and delay(...) with Thread.sleep(...). Try it (don’t forget to import kotlin.concurrent.thread).

    If you start by replacing GlobalScope.launch with thread, the compiler produces the following error:

    1. Error: Kotlin: Suspend functions are only allowed to be called from a coroutine or another suspend function

    That is because is a special suspending function that does not block a thread, but suspends the coroutine, and it can be only used from a coroutine.

    Bridging blocking and non-blocking worlds

    The first example mixes non-blocking delay(...) and blocking Thread.sleep(...) in the same code. It is easy to lose track of which one is blocking and which one is not. Let’s be explicit about blocking using the coroutine builder:

    1. import kotlinx.coroutines.*
    2. fun main() {
    3. GlobalScope.launch { // launch a new coroutine in background and continue
    4. delay(1000L)
    5. println("World!")
    6. }
    7. println("Hello,") // main thread continues here immediately
    8. runBlocking { // but this expression blocks the main thread
    9. delay(2000L) // ... while we delay for 2 seconds to keep JVM alive
    10. }

    You can get the full code here.

    The result is the same, but this code uses only non-blocking . The main thread invoking runBlocking blocks until the coroutine inside runBlocking completes.

    This example can be also rewritten in a more idiomatic way, using runBlocking to wrap the execution of the main function:

    Here runBlocking<Unit> { ... } works as an adaptor that is used to start the top-level main coroutine. We explicitly specify its Unit return type, because a well-formed main function in Kotlin has to return Unit.

    This is also a way to write unit tests for suspending functions:

    1. class MyTest {
    2. @Test
    3. fun testMySuspendingFunction() = runBlocking<Unit> {
    4. // here we can use suspending functions using any assertion style that we like
    5. }

    Delaying for a time while another coroutine is working is not a good approach. Let’s explicitly wait (in a non-blocking way) until the background Job that we have launched is complete:

    1. import kotlinx.coroutines.*
    2. fun main() = runBlocking {
    3. //sampleStart
    4. val job = GlobalScope.launch { // launch a new coroutine and keep a reference to its Job
    5. delay(1000L)
    6. println("World!")
    7. }
    8. println("Hello,")
    9. job.join() // wait until child coroutine completes
    10. //sampleEnd
    11. }

    Now the result is still the same, but the code of the main coroutine is not tied to the duration of the background job in any way. Much better.

    Structured concurrency

    There is still something to be desired for practical usage of coroutines. When we use GlobalScope.launch, we create a top-level coroutine. Even though it is light-weight, it still consumes some memory resources while it runs. If we forget to keep a reference to the newly launched coroutine, it still runs. What if the code in the coroutine hangs (for example, we erroneously delay for too long), what if we launched too many coroutines and ran out of memory? Having to manually keep references to all the launched coroutines and join them is error-prone.

    There is a better solution. We can use structured concurrency in our code. Instead of launching coroutines in the , just like we usually do with threads (threads are always global), we can launch coroutines in the specific scope of the operation we are performing.

    In our example, we have a main function that is turned into a coroutine using the runBlocking coroutine builder. Every coroutine builder, including runBlocking, adds an instance of to the scope of its code block. We can launch coroutines in this scope without having to join them explicitly, because an outer coroutine (runBlocking in our example) does not complete until all the coroutines launched in its scope complete. Thus, we can make our example simpler:

    1. import kotlinx.coroutines.*
    2. fun main() = runBlocking { // this: CoroutineScope
    3. launch { // launch a new coroutine in the scope of runBlocking
    4. delay(1000L)
    5. println("World!")
    6. }
    7. println("Hello,")
    8. }

    You can get the full code here.

    In addition to the coroutine scope provided by different builders, it is possible to declare your own scope using the builder. It creates a coroutine scope and does not complete until all launched children complete.

    runBlocking and may look similar because they both wait for their body and all its children to complete. The main difference is that the runBlocking method blocks the current thread for waiting, while just suspends, releasing the underlying thread for other usages. Because of that difference, runBlocking is a regular function and is a suspending function.

    It can be demonstrated by the following example:

    Note that right after the “Task from coroutine scope” message (while waiting for nested launch) “Task from runBlocking” is executed and printed — even though the coroutineScope is not completed yet.

    Extract function refactoring

    Let’s extract the block of code inside launch { ... } into a separate function. When you perform “Extract function” refactoring on this code, you get a new function with the suspend modifier. This is your first suspending function. Suspending functions can be used inside coroutines just like regular functions, but their additional feature is that they can, in turn, use other suspending functions (like delay in this example) to suspend execution of a coroutine.

    1. import kotlinx.coroutines.*
    2. launch { doWorld() }
    3. }
    4. // this is your first suspending function
    5. suspend fun doWorld() {
    6. delay(1000L)
    7. println("World!")
    8. }

    But what if the extracted function contains a coroutine builder which is invoked on the current scope? In this case, the suspend modifier on the extracted function is not enough. Making doWorld an extension method on CoroutineScope is one of the solutions, but it may not always be applicable as it does not make the API clearer. The idiomatic solution is to have either an explicit CoroutineScope as a field in a class containing the target function or an implicit one when the outer class implements CoroutineScope. As a last resort, CoroutineScope(coroutineContext) can be used, but such an approach is structurally unsafe because you no longer have control on the scope of execution of this method. Only private APIs can use this builder.

    Run the following code:

    1. import kotlinx.coroutines.*
    2. fun main() = runBlocking {
    3. repeat(100_000) { // launch a lot of coroutines
    4. launch {
    5. delay(5000L)
    6. print(".")
    7. }
    8. }
    9. }

    You can get the full code .

    It launches 100K coroutines and, after 5 seconds, each coroutine prints a dot.

    Now, try that with threads. What would happen? (Most likely your code will produce some sort of out-of-memory error)

    Global coroutines are like daemon threads

    The following code launches a long-running coroutine in that prints “I’m sleeping” twice a second and then returns from the main function after some delay:

    1. import kotlinx.coroutines.*
    2. fun main() = runBlocking {
    3. //sampleStart
    4. GlobalScope.launch {
    5. repeat(1000) { i ->
    6. println("I'm sleeping $i ...")
    7. delay(500L)
    8. }
    9. }
    10. delay(1300L) // just quit after delay

    You can get the full code here.

    You can run and see that it prints three lines and terminates:

    Active coroutines that were launched in do not keep the process alive. They are like daemon threads.