我是Rx的新手,仍在努力弄清楚如何正確處理觀察對象。我想知道是否有更好的方法來編寫多個特性,而不是使用RxAndroidBle一次完成一個特性?目前,我一次只做一個,代碼如下。用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;
}
因此,我改變了我的舊代碼,現在使用合併,但只有一個特性現在似乎更新。
雖然我遇到了使用合併的問題。這似乎只有一個特點被寫入這種方法。我將使用當前的代碼添加編輯。 –
看起來像其中一個observables拋出一個錯誤。 –