rx-javarxandroidble

why call the method first will disconnect automatically after discovery


I am a newer for RxJava, and when i read the demo of rxandroidble library, I am wondering why the first can disconnect the ble.

@OnClick(R.id.connect)
    public void onConnectToggleClick() {
        bleDevice.establishConnection(false)
                .flatMap(RxBleConnection::discoverServices)
                .first() // Disconnect automatically after discovery
                .compose(bindUntilEvent(PAUSE))
                .observeOn(AndroidSchedulers.mainThread())
                .doOnUnsubscribe(this::updateUI)
                .subscribe(adapter::swapScanResult, this::onConnectionFailure);

        updateUI();
    }

Solution

  • The RxAndroidBle Observable behaviour of establishConnection() states, that only a single value is emitted, while the stream is not completed. It's also stated that unsubscribing the observable disconnects the connection.

    Whenever you are no longer interested in keeping the connection open you should unsubscribe from it which will cause disconnection and cleanup of resources.

    But the first() operator emits a single value and completes the stream after. Since bindUntilEvent(PAUSE) will also complete the stream when pausing, you don't need to use first() at all. So just remove it and everything should be fine.