Liberty Tom
11/12/2024, 6:16 AMTimeout
after each 1 seconds, it just print Timeout
after each 3 seconds. So how to fix it?
fun main() = runBlocking {
repeat(5) {
try {
withTimeout(1000) {
withContext(Dispatchers.IO) {
ensureActive()
println("${Date(System.currentTimeMillis())}: Coroutine is running $it")
suspendCancellableCoroutine<Boolean> { continuation ->
continuation.resume(blockCall())
continuation.invokeOnCancellation {
println("${Date(System.currentTimeMillis())}: Coroutine is cancelled")
}
}
}
}
} catch (e: TimeoutCancellationException) {
println("${Date(System.currentTimeMillis())}: Timeout")
}
}
}
/**
* it is a block call that takes 3 seconds to complete
*/
private fun blockCall() = try {
Thread.sleep(3000)
true
} catch (e: Exception) {
false
}
ephemient
11/12/2024, 6:19 AMblockCall()
isn't suspend
so it can't be cancelledephemient
11/12/2024, 6:21 AMfun main() = runBlocking {
repeat(5) {
withTimeoutOrNull(1000) {
println("starting")
runInterruptible(Dispatchers.IO) {
blockCall()
}
} ?: println("timeout")
}
}
Liberty Tom
11/12/2024, 7:25 AMThread.sleep(3000)
. But if Thread.sleep(3000)
change to BluetoothSocket.connect() , it will timeout until the blockCall()
complete.
lifecycleScope.launch {
repeat(5) {
try {
withTimeout(1000) {
println("${Date(System.currentTimeMillis())}: starting")
runInterruptible(Dispatchers.IO) {
blockCall()
}
}
} catch (e: TimeoutCancellationException) {
// call the BluetoothSocket.close() will immediately interrupt BluetoothSocket.connect()
// BluetoothSocket.close()
println("${Date(System.currentTimeMillis())}: timeout")
}
}
}
private fun blockCall() = try {
// Thread.sleep(3000)
// it is a block call that maybe takes 10 seconds to complete
// BluetoothSocket.connect()
true
} catch (e: Exception) {
println("${Date(System.currentTimeMillis())}: exception")
false
}
ephemient
11/12/2024, 7:54 AMDanilo Herrera
11/12/2024, 1:45 PMWould callingcan be used to abort this call from another thread.close()
close()
in invokeOnCancellation
work as you expect?