Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save NeedPainkiller/680786d1712676fde61b8151c4d56c3c to your computer and use it in GitHub Desktop.
Save NeedPainkiller/680786d1712676fde61b8151c4d56c3c to your computer and use it in GitHub Desktop.
public class RxBLE2 {
private final BluetoothAdapter bluetoothAdapter;
private final BluetoothLeScanner scanner;
private Subscriber<? super BleDevice> subscriber;
private final ScanCallback callback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
subscriber.onNext(BleDevice.create(result));
}
};
public RxBLE2(Activity activity) {
BluetoothManager manager = (BluetoothManager) activity.getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = manager.getAdapter();
scanner = bluetoothAdapter.getBluetoothLeScanner();
}
public Observable<BleDevice> observe() {
if (!BluetoothHelper.IS_BLE_SUPPORTED || !bluetoothAdapter.isEnabled()) {
return Observable.empty();
}
return Observable.create(new Observable.OnSubscribe<BleDevice>() {
@Override
public void call(Subscriber<? super BleDevice> subscriber) {
RxBLE2.this.subscriber = subscriber;
scanner.startScan(callback);
}
}).distinctUntilChanged().doOnSubscribe(() -> {
if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
scanner.stopScan(callback);
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment