首页 > 解决方案 > RxBluetoothKit:如何同时订阅蓝牙状态+外围连接状态和写入/通知特性?

问题描述

我刚开始研究 RxBluetoothKit 作为与 BLE 设备交互的简单解决方案,我对 Rx 编程有非常基本的了解。

正如我从示例中看到的那样,每次我必须编写一些特性时,我都必须扫描 + 建立与外围设备的连接 + 发现服务,然后才编写并订阅此特定特性的确认。

读取特性也会发生同样的情况。

如果我理解正确,这样我就可以同时订阅一个序列/连接。

但是我需要订阅蓝牙状态和外设连接状态并通知特性,此外我有时会向同一个外设发送写命令。

需要帮助了解我应该如何使用 RXBluetoothKit 库来处理这种情况?欢迎在 GitHub 上提供类似方法的链接。谢谢!

标签: iosswiftrx-swift

解决方案


RxBluetooth 套件不涵盖这种确切的情况,因此您必须自己管理此情况。不是最理想的,但你可以使用这样的东西:

// Get an observable to the Peripheral, then share it so
// it can be used for multiple observing chains
let connectedPeripheral: Observable<Peripheral> = peripheral
    .establishConnection()
    .share(replay: 1, scope: .whileConnected)

// Establish a subscription to read characteristic first
// so no notifications are lost
let readDisposable = connectedPeripheral
    .flatMap { $0.observeValueAndSetNotification(for: Characteristic.read) }
    .subscribe()

// Write something to the write characteristic and observe
// responses in the chain above
let writeDisposable = connectedPeripheral
    .flatMap { $0.writeValue(data, for: Characteristic.write, type: .withResponse) }
    .subscribe()

上面的例子只是一个要点,但总体思路应该可行,因为我在自己的项目中做类似的事情。完成后要小心处理 observables,无论是通过 .take 还是 disposeBags。


推荐阅读