我如何使用相同的连接监听通知并使用 RxBleAndroid 发送写操作?

How can I listen for notifications and send write operations with RxBleAndroid using the same connection?

问题:

我正在使用以下代码收听通知:

bleDevice.establishConnection(false)
                .flatMap { rxBleConnection -> rxBleConnection.setupNotification(charUUID) }
                .doOnNext { }
                .flatMap { notificationObservable -> notificationObservable } // <-- Notification has been set up, now observe value changes.
                .subscribe(
                        { bytes ->
                            run {
                                // Log.i("Notification!", bytes!!.contentToString())
                                // println(bytes.toHex())
                                sp?.play(pool?.get(mRandom.nextInt(pool!!.size))!!, 1F, 1F, 0, 0, 1F)
                            }
                        },
                        { throwable -> Log.i(TAG, throwable.toString())}
                )

此通知有效。当我的设备的传感器被激活时,我能够看到通知值的变化。

现在,我想单击一个按钮并使用以下代码发送写入操作:

bleDevice.establishConnection(false)
                .flatMapSingle({ rxBleConnection -> rxBleConnection.writeCharacteristic(charUUID, bytesToWrite) })
                .subscribe(
                        { characteristicValue ->
                            run {
                                Log.d(TAG, "Write Command Succeeded")
                            }
                        },
                        { throwable ->
                            run {
                                Log.d(TAG, "Write Command Failed")
                                Log.d(TAG, throwable.toString())
                            }
                        }
                )

当我单击按钮时,我在下面的日志输出中收到了错误消息。它说我已经连接。如何在不尝试再次连接的情况下发送写入操作?

预期行为 我希望能够收听通知并在同一 Activity.

中发送写入操作

日志输出

D/ColorsFragment: Write Command Failed
    com.polidea.rxandroidble2.exceptions.BleAlreadyConnectedException: Already connected to device with MAC address 34:81:F4:C6:09:0F

您应该在所有 reads/writes 中共享相同的连接。最简单的方法是使用 RxReplayingShare:

val connection = rxBleDevice.establishConnection(false).compose(ReplayingShare.instance())

connection.subscribe({}, {}) // initiate connection

connection.flatMap({ /* do your first read/write */ }).take(1).subscribe()
connection.flatMap({ /* do your second read/write */ }).take(1).subscribe()

这种方法并不适用于所有情况,因此我建议您查看关注此问题的 documentation page