我正在尝试使用RxJS过滤React Native中的本地事件。我正在使用react-native-ble-manager公开一个EventEmitter。 基本上,没有 RxJS我正在执行以下操作(此处仅显示相关代码):
import React from 'react';
import RX from 'reactxp';
import { AppState, Platform, NativeModules, NativeEventEmitter, EmitterSubscription, PermissionsAndroid, ListView } from 'react-native';
import BleManager, { Peripheral } from 'react-native-ble-manager';
const BleManagerModule = NativeModules.BleManager;
const bleManagerEmitter = new NativeEventEmitter(BleManagerModule);
export class App extends RX.Component<IAppProps, IAppState> {
private handlerDiscover!: EmitterSubscription;
private handlerStop!:EmitterSubscription;
private handlerDisconnect!:EmitterSubscription;
private handlerUpdate!:EmitterSubscription;
componentDidMount() {
AppState.addEventListener('change', this.handleAppStateChange);
BleManager.start({ showAlert: false });
this.handlerDiscover = bleManagerEmitter.addListener('BleManagerDiscoverPeripheral', this.handleDiscoverPeripheral);
this.handlerStop = bleManagerEmitter.addListener('BleManagerStopScan', this.handleStopScan);
this.handlerDisconnect = bleManagerEmitter.addListener('BleManagerDisconnectPeripheral', this.handleDisconnectedPeripheral);
this.handlerUpdate = bleManagerEmitter.addListener('BleManagerDidUpdateValueForCharacteristic', this.handleUpdateValueForCharacteristic);
}
componentWillUnmount() {
this.handlerDiscover.remove();
this.handlerStop.remove();
this.handlerDisconnect.remove();
}
handleUpdateValueForCharacteristic = (data:any) => {
console.log('Received data from ' + data.peripheral + ' characteristic ' + data.characteristic + ' length ' + data.value.length + ' values ' + data.value);
}
}
一旦我连接到BLE外设并开始数据检索,便会使用数据调用箭头函数handleUpdateValueForCharacteristic。很好。
现在,我想使用RxJS来过滤事件,因为我每秒最多可以接收200个事件,但是我只对其中的1/4感兴趣。
我只是无法用心fromEventPattern。
到目前为止,我已经尝试过以下操作:
在类中添加了一些处理函数:
private addHandler:Function = (handler:NodeEventHandler):any => {
this.handlerUpdate = bleManagerEmitter.addListener('BleManagerDidUpdateValueForCharacteristic', handler);
return this.handlerUpdate;
}
private removeHandler:Function = (handler:EmitterSubscription, _signal?:any) => {
handler.remove();
}
在componentDidMount()中:
this.emitter = fromEventPattern<any>(this.addHandler(this.handleUpdateValueForCharacteristic), this.removeHandler(this.handlerUpdate));
this.emitter.subscribe(...);
但是订阅失败,出现以下错误:
addHandler不是函数。