Search code examples
kotlinkotlinx.coroutines

What's the non-suspending version of `Async/Await` for Kotlin Coroutines?


fun nonSuspendingFunction(): Boolean {
    return async(UI) { true }
        .await() // compiler error, can be called only within a suspending function
}

Is there a version of .await() that can be called outside a suspending function for a Deferred<T>? I'd like to block the current thread until the Deferred<T> returns.


Solution

  • runBlocking is what you're looking for.

    import kotlinx.coroutines.experimental.async
    import kotlinx.coroutines.experimental.runBlocking
    
    fun blocks() = runBlocking {
        async { true }.await()
    }
    

    I've just tested the code above with a very simple main function:

    fun main(args: Array<String>) {
        blocks().let(::println)
    }
    

    Output:

    true