-
Notifications
You must be signed in to change notification settings - Fork 52
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Connect with timeout waits unnecessarily long #70
Comments
I managed to get some code working now that does what I want it to (I think it's correct at least), but it feels a bit hacky and I'm not sure this is the best way: val scope = CoroutineScope(Dispatchers.Main)
val connect = scope.async {
withTimeout(5000) {
connection.connect()
}
}
val disconnected = scope.async {
connection.stateChanges.first {
it.newState == BluetoothProfile.STATE_DISCONNECTED
}
}
// Wait on the first job to complete:
val connected = select<Boolean> {
connect.onAwait { true }
disconnected.onAwait { false }
}
if (connected) {
// Connected!
} else {
// Connect failed due to disconnect...
} I would love feedback on how to improve this! |
Here is how a change to main...johanlunds:johanlunds-connect-change - isConnectedFlow.first { connected -> connected }
+
+ // Alternative #1: Use isConnectedFlow with accompanying change below:
+ val isConnected = isConnectedFlow.first()
+ if (!isConnected) throw GattException("Connect operation failed, got disconnected.") private val callback = object : BluetoothGattCallback() {
override fun onConnectionStateChange(gatt: BG, status: Int, newState: Int) {
- when (status) {
- STATUS_SUCCESS -> isConnected = newState == BluetoothProfile.STATE_CONNECTED
- }
+ // Alternative #1: Change the logic here to also set isConnected on failure statuses, something like:
+ isConnected = (status == STATUS_SUCCESS && newState == BluetoothProfile.STATE_CONNECTED) There's probably a reason it works like it does today that escapes me, so please feel free to let me know. |
Hi,
My issue is that sometimes connecting fails quickly with status = 133. What happens then is that
connect
andwithTimeout
waits unnecessarily long.I have connect code with timeout and stateChanges flow code as recommended. Like this:
What happens for me with status 133 is this:
disconnect()
above is executed.withTimeout
will wait the full 5 secondsTimeoutCancellationException
// Connect failed! Update UI here...
above is executedIdeally I'd like
connect
andwithTimeout
to cancel immediately and the connect call to fail immediately when the connect fails.Am I doing something wrong?
Do you have any recommendations how the code should be instead?
Thank you for a very nice library.
The text was updated successfully, but these errors were encountered: