Search code examples
androidrx-javarxandroidble

How to combine service discovery and read characteristic using RxAndroidBle


I'm new to Rx programming. I'm now trying to use RxAndroidBle to discover BLE devices' services and read some characteristics from the device.

I can use

device.establishConnection(false)
  .flatMap(rxBleConnection -> rxBleConnection.discoverServices());

to find device services

and use

device.establishConnection(false)
  .flatMap(rxBleConnection -> rxBleConnection.readCharacteristic(characteristicUUID));

to read wanted characteristic

But I'd like to know if it is possible to combine these two tasks together? If possible, how can I do it?

Many thanks for your tips and help!


Solution

  • I see that you're using a helper method readCharacteristic(UUID). You can skip the discovery at all and the library will do it for you under the hood seamlessly.

    Sure, just use flatMap with zip or publish with merge. There are many ways but this one is a basic and silly one.

     bleDevice
         .establishConnection(false)
         .flatMap(connection ->
             Observable.zip(
                 connection.readCharacteristic(UUID.randomUUID()).doOnNext(data -> doSomethingWithData(data)),
                 connection.discoverServices().doOnNext(services -> doSomethingWithServices(data)),
                 Pair::create
             )
          )
          .subscribe();
    

    It'd be best if you could do some RxJava training.