Skip to content

Commit 3aeb088

Browse files
authored
Suppress Scanner advertisement delivery failures (#68)
When `callbackFlow`'s `Channel` is closed due to downstream `Flow` being cancelled then sending to the `Channel` can unexpectedly throw an exception. We suppress the exception, as it is assumed that `Flow` is shutting down anyways.
1 parent 34e34c5 commit 3aeb088

2 files changed

Lines changed: 17 additions & 4 deletions

File tree

core/src/androidMain/kotlin/Scanner.kt

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package com.juul.kable
33
import android.bluetooth.BluetoothAdapter
44
import android.bluetooth.le.ScanCallback
55
import android.bluetooth.le.ScanResult
6+
import android.util.Log
67
import kotlinx.coroutines.cancel
78
import kotlinx.coroutines.channels.awaitClose
89
import kotlinx.coroutines.channels.sendBlocking
@@ -25,12 +26,20 @@ public class AndroidScanner internal constructor() : Scanner {
2526

2627
val callback = object : ScanCallback() {
2728
override fun onScanResult(callbackType: Int, result: ScanResult) {
28-
sendBlocking(Advertisement(result))
29+
runCatching {
30+
sendBlocking(Advertisement(result))
31+
}.onFailure {
32+
Log.w(TAG, "Unable to deliver scan result due to failure in flow or premature closing.")
33+
}
2934
}
3035

3136
override fun onBatchScanResults(results: MutableList<ScanResult>) {
32-
results.forEach {
33-
sendBlocking(Advertisement(it))
37+
runCatching {
38+
results.forEach {
39+
sendBlocking(Advertisement(it))
40+
}
41+
}.onFailure {
42+
Log.w(TAG, "Unable to deliver batch scan results due to failure in flow or premature closing.")
3443
}
3544
}
3645

core/src/jsMain/kotlin/Scanner.kt

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,11 @@ public class JsScanner internal constructor(
3131

3232
val scan = bluetooth.requestLEScan(options.toDynamic()).await()
3333
val listener: (Event) -> Unit = {
34-
offer(Advertisement(it as BluetoothAdvertisingEvent))
34+
runCatching {
35+
offer(Advertisement(it as BluetoothAdvertisingEvent))
36+
}.onFailure {
37+
console.warn("Unable to deliver advertisement event due to failure in flow or premature closing.")
38+
}
3539
}
3640
bluetooth.addEventListener(ADVERTISEMENT_RECEIVED_EVENT, listener)
3741

0 commit comments

Comments
 (0)