Kotlin Coroutines
Tags: kotlin, threads, coroutine, learnkotlinfromgde
Published: 2020-06-27 13:23:27

---
title: Kotlin Coroutines
published: true
date: 2020-04-27 17:00:00 UTC
tags: kotlin,threads,coroutine,learnkotlinfromgde
canonical_url: https://medium.com/@magdamiu/kotlin-coroutines-7938b5c7a11b
---

[Coroutines](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/index.html) are officially part of the Kotlin standard library starting with version 1.3 and they are very helpful in creating concurrent non-blocking code. They simplify async programming. Coroutines are actually lightweight threads.

![](https://cdn-images-1.medium.com/max/640/0*l3UVFLeVaD1NIOjQ)

![](https://cdn-images-1.medium.com/max/640/0*8Re1Eo11FD4-9C2K)

**Sequential execution**

![](https://cdn-images-1.medium.com/max/640/0*SMRM5Oq6gT8lK_2n)

**Parallel execution**

![](https://cdn-images-1.medium.com/max/640/0*iEjXmzzMSrKgYEWq)

**Concurrent execution**

![](https://cdn-images-1.medium.com/max/640/0*8VyFubG8F3bPeLDV)

### 📌Coroutine Scopes

A coroutine should run in a scope. The scope is used in order to track the lifecycle of the coroutine. Also it is a way to bind the coroutine(s) to an app specific lifecycle.

Behind the scope there is the concept of [structured concurrency](https://kotlinlang.org/docs/reference/coroutines/basics.html#structured-concurrency)that helps us, the developers, to avoid leaking coroutines which can waste the resources (disk, memory, cpu, network).

Structured concurrency is related to three main things:

- **Keep track** of the running coroutine
- **Cancel work** when it is not longer necessary to run it
- **Notify errors** when something bad happens to a coroutine

Every coroutine builder is an extension of [CoroutineScope](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/index.html)and inherits its coroutine context in order to propagate context elements and cancellation.

### ⛏️Coroutine Builders

Coroutine Builders are extension functions of CoroutineScope used to build and manage the execution of the coroutine.

### 🔖run()

Function definition

- lambda with a receiver
- return type is whatever the lambda returns
- there is also a non-extension version of this function

{% gist https://gist.github.com/magdamiu/e63ed9fd45aceeb01a53de8bcadd4459 %}

**The result 👇**

> Start main

> Start task1 | Thread Thread[main,5,main]

> End task1 | Thread Thread[main,5,main]

> Start task2 | Thread Thread[main,5,main]

> End task2 | Thread Thread[main,5,main]

> Called task1 and task2 from Thread[main,5,main]

> End main

### 🔖runBlocking

Function definition

- Runs a new coroutine
- Blocks current thread interruptible until its completion
- Could set a name to the coroutine for debug purposes

```
runBlocking(CoroutineName("pink-coroutine"))
```

{% gist https://gist.github.com/magdamiu/67c89d107232e7e9dd12334a50e0e3a0 %}

**The result 👇**

> Start main

> Start task1 | Thread Thread[main @coroutine#1,5,main]

> End task1 | Thread Thread[main @coroutine#1,5,main]

> Start task2 | Thread Thread[main @coroutine#1,5,main]

> End task2 | Thread Thread[main @coroutine#1,5,main]

> Called task1 and task2 from Thread[main @coroutine#1,5,main]

> End main

### 🔖launch()

Function definition

- Extension function of CoroutineScope
- Launches a new coroutine
- Does not block the current thread
- Returns a reference to the coroutine as a Job

The **Job** class represents a cancellable task that has its own lifecycle and it can also have children.

The states of job’s life cycle:

![](https://cdn-images-1.medium.com/max/640/0*iPQhD45lZgubxAFn)

{% gist https://gist.github.com/magdamiu/2a64c66ce286c2286b9eac55f1810d33 %}

**The result 👇**

> Start main

> Called task1 and task2 from Thread[main,5,main]

> Start task1 | Thread Thread[main,5,main]

> End task1 | Thread Thread[main,5,main]

> Start task2 | Thread Thread[main,5,main]

> End task2 | Thread Thread[main,5,main]

> End main

### 🔖suspend functions

Function definition

- Suspend the execution of the current task and let another task execute
- Could be called only from within a coroutine
- There are 2 functions that could help us to achieve this behavior:
- delay() => pause the currently executing task for a specific time (milliseconds)
- yield() => let other task to be executed

{% gist https://gist.github.com/magdamiu/28a7fe4816fab3b57127d710324e438c %}

**The result 👇**

> Start main

> Called task1 and task2 from Thread[main,5,main]

> Start task1 | Thread Thread[main,5,main]

> Start task2 | Thread Thread[main,5,main]

> End task1 | Thread Thread[main,5,main]

> End task2 | Thread Thread[main,5,main]

> End main

### 🔖async / await

Function definition

- **async()** is an extension function of CoroutineScope
- If we want to execute a task asynchronously and get the result, then we should use **async()** instead of launch() function.
- async() creates a new coroutine and returns its future result as an implementation of Deferred<T> which has an await() function very helpful in order to get the status of the coroutine.
- The call to await() will wait for the coroutine started by async() to complete.

{% gist https://gist.github.com/magdamiu/5e5b2d0d404a98acc0c6a14f6295659e %}

**The result 👇**

> Start main

> Awaiting the sums

> Start sumOf2

> Start sumOf3

> Total is 10

> End main

### ⛓️Coroutine Context and Threads

CoroutineContext defines the context in which the coroutine will run.

### Specific Context

When we want to run our tasks on a dedicated thread pool the solution is to use the proper dispatchers from the Dispatchers classes.

- **Dispatchers.Default**  — Different thread (if possible). It is backed by a shared pool of threads on JVM => CPU
- **Dispatchers.Main**  — Platform specific main thread (if exists) => UI/Non-blocking
- **Dispatchers.IO ** — Thread designed for offloading blocking IO tasks to a shared pool of threads => Network and disk
- **Dispatchers.Unconfined**  — Always uses the first available thread (most performant dispatcher).

{% gist https://gist.github.com/magdamiu/666efb722c6e478a10a8b780861e79aa %}

**The result 👇**

> Start main

> Start task1 | Thread Thread[DefaultDispatcher-worker-2,5,main]

> End task1 | Thread Thread[DefaultDispatcher-worker-2,5,main]

> Called task1 and task2 from Thread[main,5,main]

> Start task2 | Thread Thread[main,5,main]

> End task2 | Thread Thread[main,5,main]

> End main

### Custom pool of threads

When we want to run our tasks by using our own custom thread pool we apply the asCoroutineDispatcher function on Java’s ExecutorService.

- Executors.newSingleThreadExecutor()
- Executors.newFixedThreadPool()
- Executors.newScheduledThreadPool()
- Exectors.newCachedThreadPool()

An important thing to mention here is that the Executor should be closed because if we don’t do it our program may run infinitely. So when the coroutine(s) completes then the executor must be closed. An easy and clean way to implement this behavior is by using the use() function.

{% gist https://gist.github.com/magdamiu/3b06291cb681745455e9464eef788141 %}

**The result 👇**

> Start main

> Called task1 and task2 from Thread[main,5,main]

> Start task2 | Thread Thread[main,5,main]

> End task2 | Thread Thread[main,5,main]

> Start task1 | Thread Thread[pool-1-thread-1,5,main]

> End task1 | Thread Thread[pool-1-thread-1,5,main]

> End main

### Change the CoroutineContext

If we want to run a coroutine in one context and then change the context midway the solution is to use the withContext() function.

{% gist https://gist.github.com/magdamiu/5c19386b810bb9c9e58bfc230d003407 %}

**The result 👇**

> Start main

> Starting in Thread Thread[main,5,main]

> Start task1 | Thread Thread[DefaultDispatcher-worker-1,5,main]

> End task1 | Thread Thread[DefaultDispatcher-worker-1,5,main]

> Ending in Thread Thread[main,5,main]

> End main

> Start task2 | Thread Thread[main,5,main]

> End task2 | Thread Thread[main,5,main]

### ❌Cancelling coroutines

Coroutines can be cancelled. A coroutine is cancelled only if it is currently in a suspension point.

In order to cancel an asynchronous process running in a coroutine we could apply one the next solutions:

is an interface that has the following states ([**Job ** source](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/)):

![](https://cdn-images-1.medium.com/max/497/0*cITDxajfoheFKu9h)

[**SupervisorJob**](https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-supervisor-job.html) creates a supervisor job object in an active state. Children of a supervisor job can fail independently of each other.

### 🔖cancel()

- Cancels the Job

### 🔖join()

- Suspends the coroutine until the current job is complete

### 🔖cancelAndJoin()

- Cancels the job and suspends the invoking coroutine until the cancelled job is complete.

### 🔖withTimeout()

- Helpful to use it when a job might be taking too long
- The function runs a suspending block of code inside a coroutine and throws a TimeoutCancellationException if the timeout is exceeded

### 🔖withTimeoutOrNull

- Runs a given suspending block of code inside a coroutine with a specified timeout and returns null if this timeout was exceeded.

Code sample **cancel/join** or **cancelAndJoin**

{% gist https://gist.github.com/magdamiu/a789004a0c0202a0860c05d7af70c966 %}

**The result 👇**

> Start main

> Job is waiting 0…

> Job is waiting 1…

> Job is waiting 2…

> Job is waiting 3…

> Job is waiting 4…

> Job is waiting 5…

> Stop waiting. Let’s cancel it…

> End main

Code sample **withTimeout / withTimeoutOrNull**

{% gist https://gist.github.com/magdamiu/d6cc48aecd70b56fa5f9956ae6701c3c %}

### ✨The magic behind the scenes…

Under the hood when we use coroutines we actually work with Continuation objects. This class contains the results of the partial execution of the function so that the result can be sent to the caller by using the Continuation callback.

The compiler empowers the continuations to implement the mechanism of the coroutines, to switch the context, the threads and to restore the states.

### 📚Learn more…

- Official [documentation](https://kotlinlang.org/docs/reference/coroutines/coroutines-guide.html)
- I created this [playlist](https://www.youtube.com/playlist?list=PLaC2ibKkxGSIBdPn7QYDN5yP3pX4IpHoF) on YouTube
- Android Developers Medium articles
- [Coroutines on Android (part I)](https://medium.com/androiddevelopers/coroutines-on-android-part-i-getting-the-background-3e0e54d20bb)
- [Coroutines on Android (part II)](https://medium.com/androiddevelopers/coroutines-on-android-part-ii-getting-started-3bff117176dd)
- [Coroutines on Android (part III)](https://medium.com/androiddevelopers/coroutines-on-android-part-iii-real-work-2ba8a2ec2f45)
- [Coroutines: First things first — Android Developers](https://medium.com/androiddevelopers/coroutines-first-things-first-e6187bf3bb21)
- [Cancellation in coroutines — Android Developers](https://medium.com/androiddevelopers/cancellation-in-coroutines-aa6b90163629)
- [Exceptions in Coroutines — Android Developers](https://medium.com/androiddevelopers/exceptions-in-coroutines-ce8da1ec060c)
- [Coroutines & Patterns for work that shouldn’t be cancelled](https://medium.com/androiddevelopers/coroutines-patterns-for-work-that-shouldnt-be-cancelled-e26c40f142ad)

Check my previous articles about Kotlin:

- [Hello Kotlin](https://medium.com/@magdamiu/hello-kotlin-774b44cd9df0)
- [Kotlin Basics](https://dev.to/magdamiu/kotlin-basics-ln0)
- [Kotlin functions are fun](https://proandroiddev.com/kotlin-functions-are-fun-8fdcd4e85a5)
- [Classes in Kotlin](https://proandroiddev.com/classes-in-kotlin-9cf584556431)
- [Collections in Kotlin](https://proandroiddev.com/collections-in-kotlin-a2bd8649f697)

Enjoy and feel free to leave a comment if something is not clear or if you have questions. And if you like it please share!

Thank you for reading! 🙌🙏😍✌

Follow me on:

[Magda Miu](https://twitter.com/magdamiu)

_Originally published at_ [_http://magdamiu.com_](https://magdamiu.com/2020/04/27/kotlin-coroutines/) _on April 27, 2020._