我是 Rx 的新手,仍在试图弄清楚如何正确处理 observables。我想知道是否有更好的方法来编写多个特性而不是使用 RxAndroidBle 一次编写一个特性?目前我正在使用下面的代码一次做一个。
Observable<RxBleConnection> mConnectionObservable;
private void saveChanges(String serialNumber, Date date, MachineTypeEnum machineType, MachineConfig machineConfig) {
mWriteSubscription = mConnectionObservable
.flatMap(rxBleConnection -> Observable.merge(
getWrites(rxBleConnection, serialNumber, machineType, machineConfig, date)
))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(bytes -> {
Toast.makeText(getContext(), "Saved Changes", Toast.LENGTH_SHORT).show();
((MainActivity)getActivity()).back();
}, BleUtil::logError);
}
private Iterable<? extends Observable<? extends byte[]>> getWrites(RxBleConnection rxBleConnection,
String serialNumber,
MachineTypeEnum machineType,
MachineConfig machineConfig,
Date date) {
List<Observable<byte[]>> observables = new ArrayList<>();
observables.add(rxBleConnection.writeCharacteristic(
Constants.Bluetooth.Services.DrainCleaner.Characteristics.UUID_WRITE_SERIAL_NUMBER,
Utf8Util.nullPad(serialNumber, 16).getBytes()).doOnError(throwable -> Log.e("Write", "serial failed", throwable)));
observables.add(rxBleConnection.writeCharacteristic(
Constants.Bluetooth.Services.DrainCleaner.Characteristics.UUID_MACHINE_TYPE,
new byte[]{(byte) machineType.val()}).doOnError(throwable -> Log.e("Write", "machine type failed", throwable)));
observables.add(rxBleConnection.writeCharacteristic(
Constants.Bluetooth.Services.DrainCleaner.Characteristics.UUID_CHARACTERISTIC,
MachineConfigBitLogic.toBytes(machineConfig)).doOnError(throwable -> Log.e("Write", "machine config failed", throwable)));
observables.add(rxBleConnection.writeCharacteristic(
Constants.Bluetooth.Services.CurrentTime.Characteristics.UUID_CURRENT_TIME,
TimeBitLogic.bytesFor(date)).doOnError(throwable -> Log.e("Write", "date failed", throwable)));
return observables;
}
因此,我将旧代码更改为上面现在使用合并的代码,但现在似乎只有一个特征更新了。