kotlincoroutine

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
        }
        ...
}

Solution

  • 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