https://kotlinlang.org logo
#coroutines
Title
# coroutines
v

Vans239

08/31/2019, 9:36 PM
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.
Copy code
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?
d

Dominaezzz

08/31/2019, 9:42 PM
withTimeout
is doing what you want. It's
runBlocking
that's getting in your way.
Since the function doesn't support cancellation, do you literally just want to abandon the blocking function and let it run loose?
v

Vans239

08/31/2019, 9:44 PM
Yes, that's what I want. I understand that I'll abandon execution
d

Dominaezzz

08/31/2019, 9:45 PM
Then
GlobalScope
is your solution.
v

Vans239

08/31/2019, 9:46 PM
I don't think that this solution will work
Copy code
coroutineScope {
   val work = async { Thread.sleep(10000) }
   withTimeout(100) { work.await() }
}
Probably
GlobalScope
is indeed a right solution. Otherwise I can use custom scope
d

Dominaezzz

08/31/2019, 9:49 PM
Structured concurrency demands that a parent coroutine can only complete after it's children are complete. So any solution that can break structured concurrency will work for you. i.e
GlobalScope
, custom scope,
NonCancellable
.
👍 1
If you see yourself limiting the number of concurrent calls to this blocking function then you might want a custom scope.
4 Views