Last active
October 3, 2017 04:16
-
-
Save mikelpr/4a6797bfe7355630568fcf42ea1e87b6 to your computer and use it in GitHub Desktop.
Bluetooth LE scanner observable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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