> For the complete documentation index, see [llms.txt](https://kotlin-docs.waresix.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kotlin-docs.waresix.com/libraries/coroutines.md).

# Coroutines

## Overview

* Provided by Kotlin to support and simplify the manage of asynchronous operation.
* Coroutines are asynchronous but *not necessarily* multi threaded.

## Coroutines vs Threads

| Coroutine                          | Threads              |
| ---------------------------------- | -------------------- |
| Lightweight threads                | Expensive            |
| Managed by user                    | Managed by OS        |
| No context switching on processors | Threads are blocking |

![Threads](https://497631845-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MktelF4317XJtfJ4hCm%2Fsync%2F5d89ad69ae9db0de57486584fd3dbbd5079c66a9.png?generation=1633070633883737\&alt=media) *Threads*

![Coroutines](https://497631845-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MktelF4317XJtfJ4hCm%2Fsync%2F12852321a4a9a86e15ce791c68413b4c9e78cddc.png?generation=1633070633886083\&alt=media) *Coroutines*

## Coroutines Builder

* Coroutine have to be 'managed'. To manage a coroutine, it has to be launched inside a context which we called *builder*.
* The job of coroutine builder is launches a new coroutine concurrently with the rest of code.

### `launch`

```kotlin
launch {
    delay(1000) 
    // delay is Kotlin suspending function to pause the coroutine without blocking the thread, 
    // so that thread can now be used for other coroutines while this coroutine is paused.
    println("Hello")
}
```

* `launch` simply returns a `Job` object
* Fire and forget type, can't return data&#x20;

### `async`

* `async` returns a `Deferred` object (like `promise` and `future` in other language)
* Perform task and return result

### `runBlocking`

* `runBlocking` is a coroutine builder that runs a coroutine code, but blocks the main thread until the coroutine itself is finished.
* runBlocking can return a type
* Common place to use runBlocking is when you're writing test

## Suspend Function

* A function with suspend modifier executes the code without blocking the thread where its running.
* Only allowed to be called from coroutine blocks or other suspend function.

## Dispatcher

* Coroutine context / builder provide a *Coroutine dispatcher*.
* A Dispatcher determines which thread the coroutine is run on.
