Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
        }
        ...
}
like image 310
kurt Avatar asked Jun 29 '17 11:06

kurt


People also ask

Are Kotlin coroutines asynchronous?

Kotlin's approach to working with asynchronous code is using coroutines, which is the idea of suspendable computations, i.e. the idea that a function can suspend its execution at some point and resume later on.

Are coroutines provide asynchronous?

Coroutines are nothing but lightweight threads. They provide us with an easy way to do synchronous and asynchronous programming. Coroutines allow us to replace callbacks and build the main safety without blocking the main thread.

What is the difference between launch and async in Kotlin coroutines?

An async {} call is similar to launch {} but will return a Deferred<T> object immediately, where T is whatever type the block argument returns. To obtain a result, we would need to call await() on a Deferred. This fragment will print the output of the second coroutine before the output of the first.

When should you not use coroutines?

Answer: a. You should not use them for any foreground task.


1 Answers

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

like image 102
marstran Avatar answered Sep 26 '22 00:09

marstran