RxAndroidBle - 我可以使用单个命令将可变数量的写入组合到特性中吗?
RxAndroidBle - Can I perform combine a variable number of writes to a characteristic using a single command?
我有一个包含多条数据的数组,需要写入同一个特征,但我想在整个过程完成时得到通知。
我可以通过如下遍历数组来完成写入:
byte[][] dataArray = getDataArray();
for (byte[] values: dataArray) {
rxBleConnection.writeCharacteristic(CHARACTERISTIC_UUID, values)
.subscribe(bytes -> {
// here I am notified after each individual write
}, throwable -> {
// handle error per write
});
}
但是,这种方法很慢,我无法检测到整个写入过程何时完成。有没有办法以某种方式将写入组合在一起,以便我可以监听整个写入事务的完成?
我不能使用 Observable.merge
因为 dataArray
可能有可变大小和超过 9 个元素。
Is there a way to combine the writes together somehow so that I can listen for the completion of the entire write transaction?
是的,有办法。您可以将 byte[][]
转换为 Observable<byte[]>
,排放将在 .flatMap()
中处理。然后你只需要等待链的完成。即:
Observable.from(Arrays.asList(getDataArray()))
.flatMap(values -> rxBleConnection.writeCharacteristic(CHARACTERISTIC_UUID, values))
.ignoreElements() // transform to a `Completable` as you are interested only in the completion
.subscribe(
() -> { /* all values have been successfully written */ },
throwable -> { /* an error happened during one of the writes */ }
);
我有一个包含多条数据的数组,需要写入同一个特征,但我想在整个过程完成时得到通知。
我可以通过如下遍历数组来完成写入:
byte[][] dataArray = getDataArray();
for (byte[] values: dataArray) {
rxBleConnection.writeCharacteristic(CHARACTERISTIC_UUID, values)
.subscribe(bytes -> {
// here I am notified after each individual write
}, throwable -> {
// handle error per write
});
}
但是,这种方法很慢,我无法检测到整个写入过程何时完成。有没有办法以某种方式将写入组合在一起,以便我可以监听整个写入事务的完成?
我不能使用 Observable.merge
因为 dataArray
可能有可变大小和超过 9 个元素。
Is there a way to combine the writes together somehow so that I can listen for the completion of the entire write transaction?
是的,有办法。您可以将 byte[][]
转换为 Observable<byte[]>
,排放将在 .flatMap()
中处理。然后你只需要等待链的完成。即:
Observable.from(Arrays.asList(getDataArray()))
.flatMap(values -> rxBleConnection.writeCharacteristic(CHARACTERISTIC_UUID, values))
.ignoreElements() // transform to a `Completable` as you are interested only in the completion
.subscribe(
() -> { /* all values have been successfully written */ },
throwable -> { /* an error happened during one of the writes */ }
);