Guoqiang.Li
01/27/2025, 2:37 PMfun start() {
if (_status.value == BluetoothStatus.Scanning) return
_status.value = BluetoothStatus.Scanning
scanScope.launch {
withTimeoutOrNull(ScanDurationMillts) {
bluetoothScanner
.advertisements
.catch { cause -> _status.value = BluetoothStatus.Failed(cause.message?:"Unknown error") }
.onCompletion { cause ->
if(cause == null || cause is CancellationException) {
_status.value = BluetoothStatus.ScanStoped
}
}
.collect { advertisement ->
found = found.plus(advertisement)
_advertisements.value = found.toList()
}
}
}
}
val bluetoothScanner = Scanner {
logging {
level = Logging.Level.Events
}
filters {
match {
services = listOf(SERVICE_UUID)
// name = Filter.Name.Prefix("ED719M")
}
}
}
Guoqiang.Li
01/27/2025, 2:42 PMtravis
01/27/2025, 5:25 PMcollect
which will pull from the flow forever (or until timeout in this case).
If you're only looking for a specific (single) advertisement then I'd recommend using first
instead of collect
.
If you need to grab a few advertisements, then you can use your current collect
approach but add a takeWhile
above it that provides a false
when you want to stop scanning (when you've hit a condition that satisfies what you were scanning for).
If you need a specific number of advertisements, take(#)
can be used with your collect
.Guoqiang.Li
01/31/2025, 9:28 AMfun start() {
if (_status.value == Scanning) return // Scan already in progress.
_status.value = Scanning
scanScope.launch {
withTimeoutOrNull(SCAN_DURATION_MILLIS) {
val advertisement = scanner
.advertisements
.catch { cause ->
_status.value = ScanStatus.Failed(cause.message ?: "Unknown error") }
.onCompletion { cause ->
if (cause == null || cause is CancellationException) _status.value = Stopped }
.first()
found[advertisement.address] = advertisement
}
}
I change code to use first() but also cann't scan anything which in file ScanViewModel.kt of project sensortag .Guoqiang.Li
01/31/2025, 12:38 PM