Как реализовать классический механизм тайм-аута Bluetooth и повтора ошибок с помощью сопрограммыAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Как реализовать классический механизм тайм-аута Bluetooth и повтора ошибок с помощью сопрограммы

Сообщение Anonymous »

Я хочу реализовать классический механизм тайм-аута Bluetooth и повтора ошибок с помощью сопрограммы, я написал код ниже. Это дает мне тайм-аут каждые десять секунд вместо каждых 5 секунд.
suspend fun connectClassicBluetoothDevice() {
repeat(5) {
try {
withTimeout(5000) {
withContext(Dispatchers.IO) {
ensureActive()
println("${Date(System.currentTimeMillis())}: Coroutine is running $it")
suspendCancellableCoroutine { continuation ->
continuation.resume(blockCall())

continuation.invokeOnCancellation {
// call the BluetoothSocket.close() will immediately interrupt the blockCall()
// BluetoothSocket.close()
println("${Date(System.currentTimeMillis())}: Coroutine is cancelled")
}
}
}
}
} catch (e: TimeoutCancellationException) {
println("${Date(System.currentTimeMillis())}: timeout")
}
}
}

private fun blockCall() = try {
// it is a block call that maybe takes 10 seconds to complete
// BluetoothSocket.connect()
true
} catch (e: Exception) {
println("${Date(System.currentTimeMillis())}: exception")
false
}

Когда я меняю его на приведенный ниже код, у меня все работает хорошо, тайм-аут будет вовремя. Меня смущает, почему в приведенном выше коде тайм-аут не приходит вовремя. Так как же исправить ошибку в приведенном выше коде?
suspend fun connectClassicBluetoothDevice() {
repeat(5) {
try {
withTimeout(5000) {
ensureActive()
println("${Date(System.currentTimeMillis())}: Coroutine is running $it")
suspendCancellableCoroutine { continuation ->
thread {
continuation.resume(blockCall())
}

continuation.invokeOnCancellation {
// call the BluetoothSocket.close() will immediately interrupt the blockCall()
// BluetoothSocket.close()
println("${Date(System.currentTimeMillis())}: Coroutine is cancelled")
}
}
}
} catch (e: TimeoutCancellationException) {
println("${Date(System.currentTimeMillis())}: timeout")
}
}
}

private fun blockCall() = try {
// it is a block call that maybe takes 10 seconds to complete
// BluetoothSocket.connect()
true
} catch (e: Exception) {
println("${Date(System.currentTimeMillis())}: exception")
false
}


Подробнее здесь: https://stackoverflow.com/questions/791 ... ith-corout
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»