Introduction to coroutines
Let's start with a simple example without coroutines:
import kotlin.concurrent.thread fun main(args: Array<String>) { thread { Thread.sleep(1000) println("World!") } print("Hello ") Thread.sleep(2000) }
The thread
function executes a block of code in a different thread. Inside the block, we are simulating an expensive I/O computation (such as accessing data from a microservice over HTTP) with Thread.sleep
. Thread.sleep
will block the current thread for the number of milliseconds passed as a parameter. In this example, we don't wait until the computation finishes to keep working on other things; we print another message, "Hello"
, while the other computation is being executed. At the end, we wait for two seconds until the computation is finished.
That's not a pretty code, and we can do better:Â
fun main(args: Array<String>) { val computation = thread { Thread.sleep(1000) println("World!") } print("Hello ") ...