if `p` is `Deferred`, then I expected it to be can...
# coroutines
v
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
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
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
that’s much more readable too imo
💯 1