Kotlin Coroutines Wait Task to Complete

January 21, 2019
runBlocking or async await

Assuming you launch a coroutines on main/ui thread to display result from an heavy io operation.

launch(Dispatchers.Main) {
    val result = runBlocking(Dispatchers.IO) {
        fetchSomething()
    }

    Toast.makeText(context, result, Toast.LENGTH_LONG).show()
}

or

launch(Dispatchers.Main) {
    val queue = async(Dispatchers.IO) {
        fetchSomething()
    }
    val result = queue.await()

    Toast.makeText(context, result, Toast.LENGTH_LONG).show()
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.