scan Devices
Scans for nearby BLE devices and emits discovered devices through a reactive Flow.
This method creates a cold Flow that starts BLE scanning when collected and automatically stops scanning when the collection is cancelled. The Flow is built using callbackFlow, which bridges the callback-based Android BLE API to Kotlin's coroutine-based Flow.
Flow Behavior
Cold Flow: Scanning only begins when the Flow is actively collected. Multiple collectors will start separate scan sessions.
Automatic Cleanup: When the collector's coroutine is cancelled (e.g., when a ViewModel is cleared or a lifecycle scope ends), the scan is automatically stopped via awaitClose.
Error Handling: Scan failures are propagated as exceptions that can be caught using the Flow's catch operator.
Scan Modes
The scanSettings parameter controls how aggressively the scanner searches for devices:
ScanSettings.SCAN_MODE_LOW_POWER: Minimal battery impact, slower discovery
ScanSettings.SCAN_MODE_BALANCED: Balanced between power and latency
ScanSettings.SCAN_MODE_LOW_LATENCY: Fastest discovery, highest battery usage (default)
Thread Safety
This method is safe to call from any coroutine context. The Flow will emit results on the dispatcher of the collecting coroutine.
Error Conditions
The Flow will close with an exception in the following cases:
Bluetooth is disabled on the device
BluetoothLeScanner is unavailable (null)
The underlying scan fails (error code provided in exception message)
Return
A Flow that emits ScanResult objects for each discovered BLE device. Each ScanResult contains the android.bluetooth.BluetoothDevice, RSSI, scan record data, and other metadata about the discovered device.
Parameters
Configuration for the BLE scan behavior, including scan mode, report delay, and other parameters. Defaults to low-latency mode for fastest device discovery.
Optional list of ScanFilter objects to limit scan results to specific devices or services. An empty list (default) returns all discovered devices. Filters can match by device name, address, service UUID, manufacturer data, and more.
See also
Throws
When Bluetooth is disabled, scanner is unavailable, or scan fails.