Does kotlin coroutines have async call with timer?

Does Kotlin has possibility to call function async() in coroutines with some time, witch will return default result after time completion?

I found that it's possible to only call await, and than infinity wait the result.

async {
        ...
        val result = computation.await()
        ...
}

But real production case than you need to return either default result or exception. What is proper way to do something in Kotlin coroutines? Like something similar to this:

async {
        ...
        val timeout = 100500
        val result: SomeDeferredClass = computation.await(timeout)
        if (result.isTimeout()) {
           // get default value
        } else {
           // process result
        }
        ...
}

You can use the withTimeout -function. It will throw a CancellationException when it times out. You could catch this exception and return your default value.

Something like this:

async {
    ...
    val timeout = 100500L

    try {
        withTimeout(timeout) {
            computation.await()
        }
        ...
    } catch (ex: CancellationException) {
        defaultValue
    }
}

You could also use the withTimeoutOrNull -function, which returns null on timeout. Like this:

async {
    ...
    val timeout = 100500L
    withTimeoutOrNull(timeout) { computation.await() } ?: defaultValue
}

This approach won't let you differentiate between a timeout and a computation that returns null though. The default value would be returned in both cases.

For more info, see here: https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md#timeout


Combining both Extensions and @marstran solution I came to a solution that may fit better to your requirements of having the await function with timeout and default value. Also I think it's a cleaner solution

Just define the extension function:

suspend fun <T> Deferred<T>.await(timeout : Long, defaultValue : T) =
    withTimeoutOrNull(timeout) { await() } ?: defaultValue

And you can use it anywhere. Instead of

async {
    ...
    val timeout = 100500L
    withTimeoutOrNull(timeout) { computation.await() } ?: defaultValue
}

You can do simply

async {
    val timeout = 100500L
    computation.await(timeout, defaultValue)
}
链接地址: http://www.djcxy.com/p/53260.html

上一篇: 在C#中的typedef等效

下一篇: kotlin协同程序是否使用定时器进行异步调用?