Skip to content

Instantly share code, notes, and snippets.

@mikelpr
Last active October 3, 2017 04:16
Show Gist options
  • Save mikelpr/4a6797bfe7355630568fcf42ea1e87b6 to your computer and use it in GitHub Desktop.
Save mikelpr/4a6797bfe7355630568fcf42ea1e87b6 to your computer and use it in GitHub Desktop.
Bluetooth LE scanner observable
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import io.reactivex.Observable
import java.util.concurrent.TimeUnit
data class BLEScanResult(val dev: BluetoothDevice,
val rssi: Int,
val scanRecord: ByteArray)
fun rxBLEScanner(btAdapter: BluetoothAdapter,
duration: Long = 0,
timeUnit: TimeUnit = TimeUnit.SECONDS) = {
var scancb: BluetoothAdapter.LeScanCallback? = null
Observable.create<BLEScanResult> {emi ->
scancb = BluetoothAdapter.LeScanCallback{dev, rssi, rec -> emi.onNext(BLEScanResult(dev, rssi, rec))}
btAdapter.startLeScan(scancb)
if (duration > 0) Observable.timer(duration, timeUnit).subscribe{emi.onComplete()}
}.doFinally{btAdapter.stopLeScan(scancb)}
}()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment