Skip to content

Commit

Permalink
Improve exception message when attempting to connect a cancelled pe…
Browse files Browse the repository at this point in the history
…ripheral (#808)
  • Loading branch information
twyatt authored Dec 5, 2024
1 parent b39aef7 commit 64f054e
Show file tree
Hide file tree
Showing 6 changed files with 17 additions and 3 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@ peripheral.launch {
> ```kotlin
> peripheral.cancel()
> ```
>
> Once a [`Peripheral`] is cancelled (via `cancel`) it can no longer be used (e.g. calling `connect` will throw
> `IllegalStateException`).
> [!TIP]
> `launch`ed coroutines from a `Peripheral` object are permitted to run until `Peripheral.cancel()` is called
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ internal class BluetoothDeviceAndroidPeripheral(
}

override suspend fun connect(): CoroutineScope =
connectAction.await()
connectAction.awaitConnect()

override suspend fun disconnect() {
connectAction.cancelAndJoin(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ internal class CBPeripheralCoreBluetoothPeripheral(
}

override suspend fun connect(): CoroutineScope =
connectAction.await()
connectAction.awaitConnect()

override suspend fun disconnect() {
connectAction.cancelAndJoin(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.juul.kable

import kotlinx.coroutines.CoroutineScope

internal suspend fun SharedRepeatableAction<CoroutineScope>.awaitConnect(): CoroutineScope =
try {
await()
} catch (e: IllegalStateException) {
throw IllegalStateException("Cannot connect peripheral that has been cancelled", e)
}
1 change: 1 addition & 0 deletions kable-core/src/commonMain/kotlin/SharedRepeatableAction.kt
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ internal class SharedRepeatableAction<T>(

private suspend fun stateOrNull(): State<T>? = guard.withLock { state }

/** @throws IllegalStateException if parent [scope] is not active. */
suspend fun await() = getOrCreate().action.await()

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ internal class BluetoothDeviceWebBluetoothPeripheral(
}

override suspend fun connect(): CoroutineScope =
connectAction.await()
connectAction.awaitConnect()

override suspend fun disconnect() {
connectAction.cancelAndJoin(
Expand Down

0 comments on commit 64f054e

Please sign in to comment.