Vans239
08/31/2019, 9:36 PMwithTimeout
.
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?Dominaezzz
08/31/2019, 9:42 PMwithTimeout
is doing what you want. It's runBlocking
that's getting in your way.Vans239
08/31/2019, 9:44 PMDominaezzz
08/31/2019, 9:45 PMGlobalScope
is your solution.Vans239
08/31/2019, 9:46 PMcoroutineScope {
val work = async { Thread.sleep(10000) }
withTimeout(100) { work.await() }
}
GlobalScope
is indeed a right solution. Otherwise I can use custom scopeDominaezzz
08/31/2019, 9:49 PMGlobalScope
, custom scope, NonCancellable
.