android - 遇到 BleAlreadyConnectedException 时重新开始读取 onErrorResumeNext 中的数据
问题描述
我正在使用RXAndroidBle库连接并从 BLE 设备读取数据。我已将该establishConnection
功能设置为true
即自动连接为true。当BleAlreadyConnectedException
发生这种情况时,我想捕获该异常并重新启动读取数据流,因为每次处理和连接到 BLE 设备都会产生问题。所以最好保持连接活跃并重新读取数据。
在onErrorResumeNext
i 中重新调用函数 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();
});
解决方案
把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();
});
推荐阅读
- c - 如何用C语言写日记?
- python - TypeError:导入 sklearn 时需要一个整数(获取类型字节)
- c++ - 如何在 MacOS (OS X) 上将 GNU make 4.3 设为默认
- android - 如何实现具有弯曲角的可绘制形状
- angular - 为什么 Angular 2 从链接中删除 index.html 并重定向到我的路由链接?
- python - 需要高级 Python 书籍推荐
- javascript - Recaptcha 缺少元素“data-sitekey”,因此无法使用任何验证码服务 api
- python - Tkinter, how to get/return value by clicking a button in for-loop?
- qt - 未找到具有已注册类型的 QML 模块
- javascript - 将输入字段绑定到网格组件