ZakTaccardi
ZakTaccardi

Reputation: 12467

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.

Upvotes: 2

Views: 504

Answers (1)

ice1000
ice1000

Reputation: 6569

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

Upvotes: 3

Related Questions