visit
suspend fun doSomething(arg: Argument) {
val firstValue = sendRequest(arg)
val secondValue = sendAnotherRequest(firstValue)
}
In the example, we mark the doSomething function with the suspend keyword, which means that the answer to it will not come immediately. The function itself also executes some asynchronous requests one after another.
If we want to execute a function on the same thread, we can use runBlocking. Of course, this option will not allow us to efficiently utilize CPU resources. But it can be used in tests or command line interfaces.
fun casualFunction() {
runBlocking { suspendFunction() }
}
fun suspend suspendFunction() {
doSomething()
}
Another way is to use a separate thread pool. The example below uses Dispatchers.IO, which defaults to max(64, number of cores), but you can set a custom thread pool.
fun casualFunction() {
CoroutineScope(Dispatchers.IO).launch {
delay(1000)
println("Launch finished")
}
println("Casual function finished")
}
It is important to understand that the call to the launch block will occur in a different thread, and the method will continue its execution, so “Casual function finished” will be printed out first.
suspend fun suspendFunction() {
val context = Executors.newFixedThreadPool(10).asCoroutineDispatcher()
withContext(context) {
runSomethingSlow()
}
}
That is pretty much it to start using coroutines. You can find the complete documentation here.