Created
February 23, 2017 09:37
-
-
Save jsaund/32519e6205fc7122d6b4bca25b36628a to your computer and use it in GitHub Desktop.
Demonstration of using a RxJava to convert an asynchronous API in to a reactive one using the static helper fromEmitter
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.le.BluetoothLeScanner; | |
| import android.bluetooth.le.ScanCallback; | |
| import android.bluetooth.le.ScanResult; | |
| import android.support.annotation.NonNull; | |
| import rx.Emitter; | |
| import rx.Observable; | |
| import java.util.List; | |
| public class RxBluetoothScanner { | |
| public static class ScanResultException extends RuntimeException { | |
| public ScanResultException(int errorCode) { | |
| super("Bluetooth scan failed. Error code: " + errorCode); | |
| } | |
| } | |
| private RxBluetoothScanner() { | |
| } | |
| @NonNull | |
| public static Observable<ScanResult> scan(@NonNull final BluetoothLeScanner scanner) { | |
| return Observable.fromEmitter(scanResultEmitter -> { | |
| final ScanCallback scanCallback = new ScanCallback() { | |
| @Override | |
| public void onScanResult(int callbackType, @NonNull ScanResult result) { | |
| scanResultEmitter.onNext(result); | |
| } | |
| @Override | |
| public void onBatchScanResults(@NonNull List<ScanResult> results) { | |
| for (ScanResult r : results) { | |
| scanResultEmitter.onNext(r); | |
| } | |
| } | |
| @Override | |
| public void onScanFailed(int errorCode) { | |
| scanResultEmitter.onError(new ScanResultException(errorCode)); | |
| } | |
| }; | |
| scanResultEmitter.setCancellation(() -> scanner.stopScan(scanCallback)); | |
| scanner.startScan(scanCallback); | |
| }, Emitter.BackpressureMode.BUFFER); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment