Skip to content

Commit cb1a773

Browse files
authored
Cancel in-flight connection attempt on disconnect (#579)
1 parent 2d3874b commit cb1a773

1 file changed

Lines changed: 8 additions & 1 deletion

File tree

core/src/androidMain/kotlin/BluetoothDeviceAndroidPeripheral.kt

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import kotlinx.coroutines.flow.update
4646
import kotlinx.coroutines.job
4747
import kotlinx.coroutines.withContext
4848
import kotlin.coroutines.CoroutineContext
49+
import kotlin.coroutines.cancellation.CancellationException
4950

5051
private val clientCharacteristicConfigUuid = uuidFrom(CLIENT_CHARACTERISTIC_CONFIG_UUID)
5152

@@ -178,7 +179,13 @@ internal class BluetoothDeviceAndroidPeripheral(
178179
}
179180

180181
override suspend fun disconnect() {
181-
_connection?.bluetoothGatt?.disconnect()
182+
if (state.value is State.Connected) {
183+
// Disconnect from active connection.
184+
_connection?.bluetoothGatt?.disconnect()
185+
} else {
186+
// Cancel in-flight connection attempt.
187+
connectAction.cancelAndJoin(CancellationException(NotConnectedException()))
188+
}
182189
suspendUntil<Disconnected>()
183190
logger.info { message = "Disconnected" }
184191
}

0 commit comments

Comments
 (0)