Search code examples
rx-java2rxandroidble

Not a good way to knowingly close a connection within the `onNext` of `establishConnection` and if connection is lost, only errors occur


In the event that I'm writing a characteristic that will reboot the device, I run into a world of trouble. For example.

scanResult.bleDevice.establishConnection(false).flatMapCompletable { connection ->
        connection.writeCharacteristic(UUID, "reboot".toByteArray(Charset.defaultCharset())).ignoreElement()
}

The original establish connection never properly completes, only returns an error that the device has disconnected, which, with all other kinds of code in place to handle improper disconnections, this one becomes difficult.If I try to dispose of the connection during the onComplete of the writeCharacteristic I never seem to get a proper callback. I'm not sure that there is any specific bug with this, but rather, I'm looking for insight into how to properly


Solution

  • The question is more related to the usage of RxJava 2 than about the library. To solve your problem you would need to first keep the subscription to .establishConnection() until it will emit and a subsequent write will happen. The code could look like this:

    scanResult.bleDevice.establishConnection(false) // establish the connection
        .publish { connectionObs ->
            // it will be needed to be subscribed until something will happen on it so a need to publish
            connectionObs.takeUntil( // keep the connection subscribed until...
                connectionObs.flatMapSingle {
                    // ...the first write will complete
                    it.writeCharacteristic(
                        uuid,
                        "reboot".toByteArray(Charset.defaultCharset())
                    )
                }
            )
        }
        .ignoreElements()