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.sleepThread.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 ")
computation.join()
}

In this version, we have a reference to our thread called, computation; at the end, we wait for the join() method to finish. This is smarter than just waiting for a fixed amount of time, as real-life computations could have different execution times.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.179.85