Hi folks. I am confused with
withTimeout
.
I have a function which can block the thread for undefined time. The caller should get timeout exception after timeout. The function doesn't support cancellation. There is a similar case, but it doesn't work as described.
https://stackoverflow.com/questions/47635367/kotlin-coroutines-with-timeout/47641886#47641886
The snippet behind blocks for 10 seconds.
runBlocking {
val work = async { Thread.sleep(10000) }
withTimeout(100) {
work.await()
}
}
There are 3 solutions, which helps to make it working:
- use
GlobalScope.async
- use
async(NonCancellable + <http://Dispatchers.IO|Dispatchers.IO>)
. Scope will await for async result if i don't specify
NonCancellable
.
<http://Dispatchers.IO|Dispatchers.IO>
is needed because
runBlocking
is single threaded.
- use custom
scope
Am I missing something? Is there simpler approach?