Hi, everyone, I want to implement a timeout and re...
# getting-started
l
Hi, everyone, I want to implement a timeout and retry mechanism, I wrote blow code, but the timeout doesn’t work well, it will throw the
TimeoutCancellationException
until
blockConnect
running end.
Copy code
private suspend fun realConnectBluetoothDevice(): Boolean {
        if (bluetoothCommConnection.isConnected) {
            return true
        }

        try {
            return withTimeout(5000L) {
                for (i in 1..5) {
                    L.e("the $i times to connect bluetooth device")
                    if (blockConnect()) {
                        return@withTimeout true
                    }
                    if (i < 5) {
                        continue
                    }
                }
                throw CommConnectionException("connect bluetooth device failed")
            }
        } catch (e: TimeoutCancellationException) {
            bluetoothCommConnection.closeImmediately()
            throw e
        }
    }

    private suspend fun blockConnect() = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
        try {
            bluetoothCommConnection.open()
            bluetoothCommConnection.isConnected
        } catch (e: CommConnectionException) {
            false
        }
    }
y
You might get better luck asking in #C1CFAFJSK
🫡 1