Skip to content

Instantly share code, notes, and snippets.

@RobLewis
Last active March 19, 2018 22:30
Show Gist options
  • Save RobLewis/a0b879c5db3bdd1a71e6562117f857f3 to your computer and use it in GitHub Desktop.
Save RobLewis/a0b879c5db3bdd1a71e6562117f857f3 to your computer and use it in GitHub Desktop.
Managing BLE connections with RxAndroidBle (RxJava2 version)
/*
The RxJava2-compatible version of the great Android Bluetooth LE library RxAndroidBle is out.
There are some changes I found a bit confusing and I'm hoping the discussion and code here
may help others.
The authors have retained the convention that the device.establishConnection() method
returns an Observable that emits one item: the connection to the Bluetooth device.
This Observable<RxBleConnection> may signal errors like "timeout" or "already connected"
but--importantly--it will NEVER call the Subscriber's .onComplete() handler.
Since there can only be one connection to a BLE device, it might seem logical that
.establishConnection() would return a Single<RxBleConnection>, or perhaps a Maybe<RxBleConnection>;
however this would sacrifice one very convenient feature: all you have to do to tear down the connection
is unsubscribe (or in RxJava2-speak, "dispose") the Subscription (in RxJava2, "Disposable").
With a Single or Maybe, the Subscription would be automatically disposed as soon as the item (connection)
was emitted. Some other way would have to be found to disconnect.
In code:
// To connect and process the connection:
Disposable connectionDisp = device.establishConnection( autoConnect ).subscribe( this::handleConnection );
// To disconnect
connectionDisp.dispose();
This all works the same in both the RxJava1 and RxJava2 versions of RxAndroidBle (except for the terminology).
What's different is the reading and writing of BLE Characteristics once the connection has been established.
Previously, the .readCharacteristic() and .writeCharacteristic() methods returned a 1-item COMPLETING
Observable<byte[]>--it would call .onNext( value ) and then call .onCompleted() (which automatically canceled
the Subscription). In the new version, these are replaced by Single<byte[]>.
A Single makes only one call to its Subscriber--either .onSuccess( value ), or .onError( error )--and then
cancels (disposes) the subscription (Disposable).
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment