Skip to content

Instantly share code, notes, and snippets.

@nhaarman
Last active April 12, 2018 07:27
Show Gist options
  • Save nhaarman/28c941b5e9d9252be329803059991936 to your computer and use it in GitHub Desktop.
Save nhaarman/28c941b5e9d9252be329803059991936 to your computer and use it in GitHub Desktop.
data class Device(
val name: String
)
interface DeviceScanner {
/** Emits a Device opon each new discovery event */
fun devices() : Observable<Device>
}
class BluetoothDeviceScanner(
private val bluetoothLeScanner: BluetoothLeScanner
) : DeviceScanner {
override fun devices(): Observable<Device> {
return Observable
.create { emitter ->
val callback = object : ScanCallback(), Cancellable {
override fun onScanResult(callbackType: Int, result: ScanResult) {
emitter.onNext(Device(result.device.name))
}
override fun cancel() {
bluetoothLeScanner.stopScan(this)
}
}
bluetoothLeScanner.startScan(callback)
emitter.setCancellable(callback)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment