我正在使用RxAndroidBle做一个可作为呼吸机遥控器的应用程序。我对unsubscribe
有疑问,因为当我使用
.flatMap(rxBleConnection -> rxBleConnection.writeCharacteristic(Uuids.UUID_RX, flaktCommandConcat.getBytes()))
之后我使用subscription.unsubscribe();
writeCharacteristics不起作用,因为unsubscribe
始终先运行,连接在数据发送之前断开连接。
我需要的是:
有人可以帮助我一些想法吗?我尝试使用.delay(1000, Time.MILISECONDS)
并且它有效,但需要很长时间才能将信息发送到呼吸机。
这是我的代码:
public void writeRxCharacteristics(String flaktCommandConcat){
rxBleDevice = rxBleClient.getBleDevice(Uuids.DEVICE_ADDRESS);
subscription = rxBleDevice.establishConnection(true) //false
.observeOn(AndroidSchedulers.mainThread())
.flatMap(rxBleConnection -> rxBleConnection.createNewLongWriteBuilder()
.setCharacteristicUuid(Uuids.UUID_RX)
.setBytes(flaktCommandConcat.getBytes())
.build())
.subscribe(
byteArray -> {
Log.d("CharacteristicValue","WRITE: " + Arrays.toString(byteArray));
},
throwable -> {
Log.d("CharacteristicValue","Throwable: " + throwable.toString());
rxBleActivity.onScanFailure(throwable, getContext());
}
);
rxBleDevice.observeConnectionStateChanges()
.observeOn(AndroidSchedulers.mainThread())
.delay(1000, TimeUnit.MILLISECONDS)
.subscribe(
rxBleConnectionState -> {
Log.d("RxBleConnectionState", " CON_STATUS: " + rxBleConnectionState);
disconnect();
},
throwable -> {
Log.d("ConnectionStateChanges","Throwable: " + throwable.toString());
}
);
}
public void disconnect() {
if (subscription != null && !subscription.isUnsubscribed()) {
subscription.unsubscribe();
subscription = null;
}
Log.d("CONNECTION2", " CON_STATUS: " + rxBleDevice.getConnectionState().toString());
}
答案 0 :(得分:0)
看起来你不需要长写。您的数据是否超过20个字节?
无论如何,当Observable<RxBleConnection>
取消订阅时,库会释放连接。如果我是你,我会做的是:
public void writeRxCharacteristics(String flaktCommandConcat){
rxBleDevice = rxBleClient.getBleDevice(Uuids.DEVICE_ADDRESS);
rxBleDevice.establishConnection(true) //false
.flatMap(rxBleConnection -> rxBleConnection.createNewLongWriteBuilder()
.setCharacteristicUuid(Uuids.UUID_RX)
.setBytes(flaktCommandConcat.getBytes())
.build()
)
.take(1)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
byteArray -> {
Log.d("CharacteristicValue","WRITE: " + Arrays.toString(byteArray));
},
throwable -> {
Log.d("CharacteristicValue","Throwable: " + throwable.toString());
rxBleActivity.onScanFailure(throwable, getContext());
}
);
请确保你没有过度使用长写。它在1.2.0中有一个已知错误(无关),最近在1.3.0-SNAPSHOT中修复。