Search code examples
rx-javarx-androidrxandroidble

Why can't it apply flatmap and subscribe on the same RxBleConnection observable twice?


As title,

For simplicity, if i want to execute twice read operation with different UUID :

(I know RxAndroidBle have provided a multiple read function)

Observable<RxBleConnection> ob = device.establishConnection(false);

ob.flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(CHAR_WIFI_SSID))
        .subscribe(
                characteristicValue -> {
                    //2. then read Successfully here !!!!!
                },
                throwable -> {
                }
        );

ob.flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(CHAR_WIFI_SECURITY_MODE))
        .subscribe(
                characteristicValue -> {     
                },
                throwable -> {
                    //1. I got BleAlreadyConnectedException error first !!!!
                }
        );

Why does second subscribe() get BleAlreadyConnectedException ?

==========update==========

i found the solution, if i modify

device.establishConnection(false) ==> device.establishConnection(false).compose(new ConnectionSharingAdapter())

ConnectionSharingAdapter will do something like this:

sourceObservable.replay(1).refCount();

keep the last one emitted by source observable


Solution

  • Subscribing twice to the same Observable will invoke subscription logic twice, which can be redundant at some cases or faulty like your case, where you are establishing multiple connections to Ble which is forbidden and got the BleAlreadyConnectedException.
    as Dean Xu pointed out, you should multicast your Observable to prevent that. (you can use various publish/share operators)