Coroutines

Coroutines allow us to write asynchronous code in a sequential fashion without the use of callbacks. They are a part of the Kotlin language, and are now the default, Kotlin-idomatic way to write non-blocking code.

The following snippet demonstrates a basic example of using coroutines:

fun main() {
GlobalScope.launch {
delay(500)
println("Coroutines")
}
println("Hello")
Thread.sleep(1000)
}

In this example, a new coroutine is started by calling GlobalScope.launch { }. This code will be run in the background without blocking the starting thread. This code will produce the following output:

Hello
Coroutines

Because the launched coroutine doesn't block, Hello will be printed before the Coroutines line is printed within the coroutine. 

Now that we've understood these async patterns, in the next section, we will see how we can build on our understanding of coroutines by looking at what they are and how they can be used.