https://kotlinlang.org logo
v

vaskir

07/03/2017, 1:06 PM
Copy code
suspend fun <T> withTimeout(timeout: Long, units: TimeUnit, f: () -> Deferred<T>) : T? =
    select<T?> {
        f().onAwait { it }
        onTimeout(timeout, units) { null }
    }

fun f() = runBlocking {
    withTimeout(3, TimeUnit.SECONDS) {
        async(CommonPool) {
            delay(2, TimeUnit.SECONDS)
            "foo"
        }
    }
}