Created
May 24, 2016 08:32
-
-
Save NeedPainkiller/680786d1712676fde61b8151c4d56c3c to your computer and use it in GitHub Desktop.
This file contains 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
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