首页 > 解决方案 > 遇到 BleAlreadyConnectedException 时重新开始读取 onErrorResumeNext 中的数据

问题描述

我正在使用RXAndroidBle库连接并从 BLE 设备读取数据。我已将该establishConnection功能设置为true即自动连接为true。当BleAlreadyConnectedException发生这种情况时,我想捕获该异常并重新启动读取数据流,因为每次处理和连接到 BLE 设备都会产生问题。所以最好保持连接活跃并重新读取数据。

onErrorResumeNexti 中重新调用函数 writeStatus、readModelInfo、getReadings 等。现在确定我将如何实现它。

   device.establishConnection(true)
        .flatMap(rxBleConnection -> {
            rxBleConnection.discoverServices();
            mRxBleConnection = rxBleConnection;
            return Observable.just(rxBleConnection);
        })
        .flatMap(rxBleConnection -> rxBleConnection.setupNotification(TSDictionary.BATTERY_LEVEL,NotificationSetupMode.QUICK_SETUP).flatMap(it->it))
        .flatMap(bytes -> writeStatus())
        .flatMap(bytes->readModelInfo(bytes))
        .flatMap(bytes -> getReadings(bytes))
        .doOnNext(data->initializeErrorHistory(data))
        .flatMap(data->getSequenceSize())
        .flatMap(length ->getOperationInfo(length))
        .doOnNext(data->initializeOperationInfo(data))
        .onErrorResumeNext(new Function<Throwable, ObservableSource<? extends ArrayList<Map<Integer, TSDictionaryMetaData>>>>() {
            @Override
            public ObservableSource<? extends ArrayList<Map<Integer, TSDictionaryMetaData>>> apply(@io.reactivex.annotations.NonNull Throwable throwable) throws Exception {

                if(throwable instanceof  BleAlreadyConnectedException){

                    // i want to RECALL/restart the  function call 
                    // writeStatus ,readModelInfo,getReadings, initializeErrorHistory
                    // getSequenceSize , getOperationInfo, initializeOperationInfo
                }
                return null;
            }
        })
        .subscribe(data -> {

        }, e -> {
            e.printStackTrace();
        });

标签: androidbluetooth-lowenergyrx-java2android-bluetoothrxandroidble

解决方案


onErrorResumeNext更接近的连接代码。

device.establishConnection(true)
.doOnNext(rxBleConnection -> {
    rxBleConnection.discoverServices();
    mRxBleConnection = rxBleConnection;
})
.onErrorResumeNext(throwable -> {
     if (throwable instanceof BleAlreadyConnectedException) {
        return Observable.just(mRxBleConnection);
     }
     return Observable.error(throwable);
})
.flatMap(rxBleConnection -> 
     rxBleConnection.setupNotification(TSDictionary.BATTERY_LEVEL,
         NotificationSetupMode.QUICK_SETUP)
    .flatMap(it->it)
)
.flatMap(bytes -> writeStatus())
.flatMap(bytes->readModelInfo(bytes))
.flatMap(bytes -> getReadings(bytes))
.doOnNext(data->initializeErrorHistory(data))
.flatMap(data->getSequenceSize())
.flatMap(length ->getOperationInfo(length))
.doOnNext(data->initializeOperationInfo(data))
.subscribe(data -> {

}, e -> {
    e.printStackTrace();
});

推荐阅读