@@ -41,6 +41,7 @@ import kotlinx.coroutines.delay
4141import kotlinx.coroutines.flow.MutableStateFlow
4242import kotlinx.coroutines.flow.StateFlow
4343import kotlinx.coroutines.flow.asStateFlow
44+ import kotlinx.coroutines.flow.buffer
4445import kotlinx.coroutines.flow.catch
4546import kotlinx.coroutines.flow.filterNot
4647import kotlinx.coroutines.flow.filterNotNull
@@ -49,6 +50,7 @@ import kotlinx.coroutines.flow.map
4950import kotlinx.coroutines.flow.onCompletion
5051import kotlinx.coroutines.flow.onEach
5152import kotlinx.coroutines.flow.onEmpty
53+ import kotlinx.coroutines.flow.onStart
5254import kotlinx.coroutines.flow.update
5355import kotlinx.coroutines.launch
5456import kotlinx.coroutines.withTimeout
@@ -61,13 +63,11 @@ import no.nordicsemi.kotlin.ble.core.ConnectionState
6163import no.nordicsemi.kotlin.ble.core.Phy
6264import no.nordicsemi.kotlin.ble.core.PhyInUse
6365import no.nordicsemi.kotlin.ble.core.WriteType
64- import no.nordicsemi.kotlin.ble.core.util.fromShortUuid
6566import timber.log.Timber
6667import javax.inject.Inject
6768import kotlin.time.Duration.Companion.milliseconds
6869import kotlin.time.Duration.Companion.seconds
6970import kotlin.uuid.ExperimentalUuidApi
70- import kotlin.uuid.Uuid
7171
7272@HiltViewModel
7373class ScannerViewModel @Inject constructor(
@@ -102,29 +102,27 @@ class ScannerViewModel @Inject constructor(
102102
103103 @OptIn(ExperimentalUuidApi ::class )
104104 fun onScanRequested () {
105- _isScanning .update { true }
106105 scanningJob = centralManager
107106 .scan(5000 .milliseconds) {
108- Any {
109- ManufacturerData (0x0059 )
110- ServiceUuid (Uuid .fromShortUuid(0x1809 ))
111- }
107+ // Any {
108+ // ManufacturerData(0x0059)
109+ // ServiceUuid(Uuid.fromShortUuid(0x1809))
110+ // }
112111 Any {
113112 Name (" Pixel 5" )
114113 Name (" Pixel 7" )
115- Name (" Nordic_LBS" )
116- Name (" Nordic_Buttonless" )
117114 Name (" DFU1A06" )
118- Name (" Mesh Light" )
119115 Name (" nRFConnect" )
120116 Name (" HR Sensor" )
121117 Name (Regex (" Mesh.*" ))
118+ Name (Regex (" Nordic.*" ))
122119 }
123120 }
124- .distinctByPeripheral()
125- .map {
126- it.peripheral
121+ .onStart {
122+ _isScanning .update { true }
127123 }
124+ .distinctByPeripheral()
125+ .map { it.peripheral }
128126 .filterNot { _devices .value.contains(it) }
129127 // .distinct()
130128 .onEach { newPeripheral ->
@@ -185,6 +183,7 @@ class ScannerViewModel @Inject constructor(
185183 observerServices(peripheral, this )
186184 } catch (e: Exception ) {
187185 Timber .e(e, " Connection attempt failed" )
186+ connectionScopeMap.remove(peripheral)?.cancel()
188187 }
189188 }
190189 }
@@ -356,6 +355,7 @@ class ScannerViewModel @Inject constructor(
356355
357356 private fun observePeripheralState (peripheral : Peripheral , scope : CoroutineScope ) {
358357 peripheral.state
358+ .buffer()
359359 .onEach {
360360 Timber .i(" State of $peripheral : $it " )
361361
0 commit comments