RxBluetoothKit:如何同时订阅蓝牙状态+外围连接状态和写入/通知特性?

问题描述 投票:0回答:1

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

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

读取特征时也会发生。

如果我理解正确,那么我只能同时订阅一个序列/连接。

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

需要帮助以了解如何使用RXBluetoothKit库处理这种情况?欢迎链接到GitHub上的类似方法。谢谢!

ios swift rx-swift rxbluetooth
1个回答
0
投票

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()

上面的示例仅是要点,但总体思路应该可行,因为我正在自己的项目中做类似的事情。完成后,请小心通过.take或disposeBags处置可观察对象。

© www.soinside.com 2019 - 2024. All rights reserved.