如何从 RxAndroidBle 获取 BluetoothGatt 对象

How to obtain BluetoothGatt object from RxAndroidBle

据报道 here,我有一个遗留应用程序拒绝连接到我试图支持的外围设备之一(与其他外围设备工作正常)。 RxAndroidBle 也连接成功,我正在考虑使用它来建立连接并将其交给应用程序的其余部分。我需要从 RxBleConnection 中获取 BluetoothGatt 对象;我怎样才能做到这一点?

目前获取BluetoothGatt实例的唯一选择是实现RxBleCustomOperation接口并在RxBleConnection.queue(RxBleCustomOperation)

上使用它
public interface RxBleCustomOperation<T> {

  /**
   * (...)
   */
  @NonNull
  Observable<T> asObservable(BluetoothGatt bluetoothGatt,
                             RxBleGattCallback rxBleGattCallback,
                             Scheduler scheduler) throws Throwable;
}

注意 RxBleCustomOperation 接口和 RxBleConnection.queue(RxBleCustomOperation) 函数上的 Javadoc。

在仔细研究了文档之后,我希望我做对了。广泛的评论是为了我自己的利益,但也许他们会帮助其他人试图理解这一点。欢迎评论和指正。

public class GetGattOperation implements RxBleCustomOperation<BluetoothGatt> {

    private BluetoothGatt gatt;

    // How this may work:

    // You call rxBleConnection.queue( <instance of this class> )
    // It returns an Observable<T>--call it Observable A

    // The queue manager calls the .asObservable() method below,
    // which returns another Observable<T>--Observable B
    // It is placed in the queue for execution

    // When it's time to run this operation, ConnectionOperationQueue will
    // subscribe to Observable B (here, Observable.just( bluetoothGatt ))

    // Emissions from this Observable B (here, the bluetoothGatt) are forwarded to the Observable A returned by .queue()

    // Instances can be queued and received via a subscription to Observable A: 
    // rxBleConnection.queue( new GetGattOperation() ).subscribe( gatt -> {} );

    @Override
    public @NonNull Observable<BluetoothGatt> asObservable( BluetoothGatt bluetoothGatt,
                                                            RxBleGattCallback rxBleGattCallback,
                                                            Scheduler scheduler) throws Throwable {

        gatt = bluetoothGatt;
        return Observable.just( bluetoothGatt );  // return Observable B
    }


    public BluetoothGatt getGatt( ) {
        return gatt;
    }

}

主程序像这样使用它(在 .establishConnection() 运算符链中):

.doOnNext( connection -> {
    rxBleConnection = connection;
    connection.queue( new GetGattOperation() )  // queue() returns Observable A
        .subscribe( gatt -> {  // receives events forwarded from Observable B
            Log.i( "Main", "BluetoothGatt received: " + gatt.toString() );
        } );
    } 
)