如何用react-native-ble-plx的subscription.remove()停止BLE数据监听?
嘿,这个问题其实很容易解决——你只需要把monitorCharacteristicForService返回的订阅对象保存下来,在需要停止的时候调用它的remove()方法就行!我帮你一步步修改代码:
第一步:保存订阅引用
首先,在你的组件类里添加两个变量,用来存储BLE特征的监听订阅。你可以在构造函数里初始化它们:
constructor(props) { super(props); this.state = { acc_dx: [], array_acc_dx: [], pressure_dx: [], array_pressure_dx: [], }; // 初始化订阅变量,用来保存监听的引用 this.accSubscription = null; this.pressureSubscription = null; }
第二步:把订阅赋值给变量
修改你的setupNotifications1方法,把monitorCharacteristicForService的返回值存到刚才定义的变量里:
async setupNotifications1(device) { var timeagm = 0 var time = 0 const service = this.serviceGeneral(); // 保存加速度计特征的订阅 this.accSubscription = await device.monitorCharacteristicForService( service, this.AccGyrMg, (error, characteristic) => { if (error) { this.error(error.message); return; } const buf = Buffer.from(characteristic.value, "base64"); const [...acc_dx] = [2, 4, 6].map(index => buf.readInt16LE(index)); this.setState(state => ({ acc_dx, array_acc_dx: [...state.array_acc_dx, [timeagm, acc_dx]] })); timeagm += 20 } ); // 保存压力特征的订阅 this.pressureSubscription = await device.monitorCharacteristicForService( service, this.Pressure, (error, characteristic) => { if (error) { this.error(error.message); return; } const buf = Buffer.from(characteristic.value, "base64"); const [...pressure_dx] = [0, 2, 4, 6, 8].map(index => buf.readUInt16LE(index)); this.setState(state => ({ pressure_dx, array_pressure_dx: [...state.array_pressure_dx, [time, pressure_dx]] })); time += 20 } ); }
第三步:在停止按钮点击时调用remove()
现在修改stopConnection方法,在跳转页面之前,调用两个订阅的remove()方法来停止监听:
stopConnection() { console.log("Inizio stopConnection"); // 停止加速度计的监听 if (this.accSubscription) { this.accSubscription.remove(); this.accSubscription = null; // 清空引用,避免后续误调用 } // 停止压力传感器的监听 if (this.pressureSubscription) { this.pressureSubscription.remove(); this.pressureSubscription = null; } // 传递数据并跳转页面 Actions.registerattivita( { array_acc_dx: this.state.array_acc_dx, array_pressure_dx: this.state.array_pressure_dx, } ) }
额外提醒:组件卸载时清理订阅
为了避免内存泄漏,建议在组件卸载的时候也停止监听。如果是类组件,可以在componentWillUnmount里处理:
componentWillUnmount() { // 清理所有订阅 if (this.accSubscription) { this.accSubscription.remove(); } if (this.pressureSubscription) { this.pressureSubscription.remove(); } }
这样修改后,点击停止按钮时就会同时停止BLE特征的监听,不会再继续接收数据啦!
内容的提问来源于stack exchange,提问作者Jack23
相关产品推荐
相关产品推荐

