Liberty Tom
11/04/2024, 5:38 AMCommConnectionException
but never throw the TimeoutCancellationException
. So why the timeout doesn’t work well? How to fix it?
private suspend fun realConnectBluetoothDevice(): Boolean {
if (bluetoothCommConnection.isConnected) {
return true
}
repeat(5) {
L.e("the $it times to connect bluetooth device")
try {
return@realConnectBluetoothDevice blockConnect(5000L)
} catch (e: CommConnectionException) {
if (it == 4) {
throw e
}
} catch (e: TimeoutCancellationException) {
if (it == 4) {
throw e
}
}
}
throw CommConnectionException("connect bluetooth device failed")
}
private suspend fun blockConnect(timeout: Long) = try {
withTimeout(timeout) {
withContext(Dispatchers.IO) {
try {
bluetoothCommConnection.open()
// bluetoothCommConnection.isConnected is a Boolean value
bluetoothCommConnection.isConnected
} catch (e: CommConnectionException) {
bluetoothCommConnection.closeImmediately()
throw e
}
}
}
} catch (e: TimeoutCancellationException) {
bluetoothCommConnection.closeImmediately()
throw e
}
Robert Williams
11/04/2024, 10:00 AMRobert Williams
11/04/2024, 10:09 AMbluetoothCommConnection
supports Java interruptions you may get expected behaviour by replacing withContext
with runInterruptible
Liberty Tom
11/04/2024, 10:13 AMLiberty Tom
11/04/2024, 10:15 AMbluetoothCommConnection.closeImmediately()
will interrupt the bluetoothCommConnection.open()
and return immediatelyRobert Williams
11/04/2024, 1:52 PMsuspendCancellableCoroutine {
it.invokeOnCancellation{
interruptMethod()
}
it.resume(blockingMethod()) {
}
}