David Carek David Carek - 27 days ago 10
Android Question

What is the proper way to write multiple characteristics with RxAndroidBle?

I'm new to Rx and still trying to figure out how to properly handle observables. I was wondering if there is a better way to write multiple characteristics than to do them one at a time with RxAndroidBle? Currently I'm doing them one at a time with the code down below.

Observable<RxBleConnection> mConnectionObservable;

mConnectionObservable
.flatMap(rxBleConnection -> rxBleConnection
.writeCharacteristic(
Constants.Bluetooth.Services.DeviceInformation.Characteristics.UUID_SERIAL_NUMBER,
Utf8Util.nullPad(serialNumber, 16).getBytes()
))
.subscribe(bytes -> {/* do something*/}, BleUtil::logError);

mConnectionObservable.flatMap(rxBleConnection -> rxBleConnection
.writeCharacteristic(
Constants.Bluetooth.Services.DrainCleaner.Characteristics.UUID_MACHINE_TYPE,
new byte[]{(byte) machineType.val()}
))
.subscribe(bytes -> {/* do something*/}, BleUtil::logError);

Answer Source

I would use merge operator:

mConnectionObservable
        .flatMap(rxBleConnection -> 
        Observable.merge(
        rxBleConnection.writeCharacteristic(
            Constants.Bluetooth.Services.DeviceInformation.Characteristics.UUID_SERIAL_NUMBER,
            Utf8Util.nullPad(serialNumber, 16).getBytes()
        ),
        rxBleConnection.writeCharacteristic(
            Constants.Bluetooth.Services.DrainCleaner.Characteristics.UUID_MACHINE_TYPE,
            new byte[]{(byte) machineType.val()}
        ))
        .subscribe(bytes -> {/* do something*/}, BleUtil::logError);

Also you could pass a list of observables to that operator:

Instead of passing multiple Observables (up to nine) into merge, you could also pass in a List<> (or other Iterable) of Observables, an Array of Observables, or even an Observable that emits Observables, and merge will merge their output into the output of a single Observable