@ NonNull private Single < BluetoothGatt > getConnectedBluetoothGatt ( ) { // start connecting the BluetoothGatt // note: Due to different Android BLE stack implementations it is not certain whether `connectGatt()` or `BluetoothGattCallback` // will emit BluetoothGatt first return Single . create ( new SingleOnSubscribe < BluetoothGatt > ( ) { @ Override public void subscribe ( final SingleEmitter < BluetoothGatt > emitter ) throws Exception { final DisposableSingleObserver < BluetoothGatt > disposableGattObserver = getBluetoothGattAndChangeStatusToConnected ( ) // when the connected state will be emitted bluetoothGattProvider should contain valid Gatt . delaySubscription ( rxBleGattCallback . getOnConnectionStateChange ( ) . filter ( new Predicate < RxBleConnection . RxBleConnectionState > ( ) { @ Override public boolean test ( RxBleConnection . RxBleConnectionState rxBleConnectionState ) throws Exception { return rxBleConnectionState == CONNECTED ; } } ) ) // disconnect may happen even if the connection was not established yet . mergeWith ( rxBleGattCallback . < BluetoothGatt > observeDisconnect ( ) . firstOrError ( ) ) . firstOrError ( ) . subscribeWith ( disposableSingleObserverFromEmitter ( emitter ) ) ; emitter . setDisposable ( disposableGattObserver ) ; connectionStateChangedAction . onConnectionStateChange ( CONNECTING ) ; /* * Apparently the connection may be established fast enough to introduce a race condition so the subscription * must be established first before starting the connection. * https://github.com/Polidea/RxAndroidBle/issues/178 * */ final BluetoothGatt bluetoothGatt = connectionCompat . connectGatt ( bluetoothDevice , autoConnect , rxBleGattCallback . getBluetoothGattCallback ( ) ) ; /* * Update BluetoothGatt when connection is initiated. It is not certain * if this or RxBleGattCallback.onConnectionStateChange will be first. * */ bluetoothGattProvider . updateBluetoothGatt ( bluetoothGatt ) ; } } ) ; }
Emits BluetoothGatt and completes after connection is established .