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

vaskir

06/04/2020, 4:06 PM
if
p
is
Deferred
, then I expected it to be cancelled on timeout:
Copy code
select<Unit> {
    p.onAwait { println("ok") }
    onTimeout(1000) { println("timed out!") }
}
but it's not, it prints "timeout out!",
p
is not cancelled. What is the best way to cancel a
Deferred
by timeout?
z

Zach Klippenstein (he/him) [MOD]

06/04/2020, 4:26 PM
Call
p.cancel()
from your
onTimeout
block? Alternatively, if
p
is a child of the current scope, maybe you have more than one, then you can call
scope.coroutineContext.cancelChildren()
.
v

vaskir

06/04/2020, 5:18 PM
Copy code
withTimeout(1000) {
    p.await()
}
🙂 This throws
Copy code
Exception in thread "main" kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 1000 ms
	at kotlinx.coroutines.TimeoutKt.TimeoutCancellationException(Timeout.kt:158)
	at kotlinx.coroutines.TimeoutCoroutine.run(Timeout.kt:128)
	at kotlinx.coroutines.EventLoopImplBase$DelayedRunnableTask.run(EventLoop.common.kt:497)
	at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.common.kt:274)
	at kotlinx.coroutines.DefaultExecutor.run(DefaultExecutor.kt:68)
	at java.base/java.lang.Thread.run(Thread.java:834)
which is what I need.
IDEA suggested to simplify it, so it become
Copy code
withTimeout(1000) {
    runCommand("cmd.exe", File("."))
}
🙂
awesome
the process is indeed killed 🙂
z

Zach Klippenstein (he/him) [MOD]

06/04/2020, 5:45 PM
that’s much more readable too imo
💯 1
6 Views