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
}
...
}
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.
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.
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.
Answer: a. You should not use them for any foreground task.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With