Typescript RxJS fromEventPattern与React本机事件
我试图在React native with RxJS中过滤本机事件。我使用的是react-native ble管理器,它公开了一个EventEmitter。 基本上,没有RxJS,我将执行以下操作(此处仅显示相关代码): 在componentDidMount()中:Typescript RxJS fromEventPattern与React本机事件,typescript,rxjs,reactxp,Typescript,Rxjs,Reactxp,我试图在React native with RxJS中过滤本机事件。我使用的是react-native ble管理器,它公开了一个EventEmitter。 基本上,没有RxJS,我将执行以下操作(此处仅显示相关代码): 在componentDidMount()中: this.emitter=fromEventPattern(this.addHandler(this.handleUpdateValueForCharacteristic)、this.removeHandler(this.handl
this.emitter=fromEventPattern(this.addHandler(this.handleUpdateValueForCharacteristic)、this.removeHandler(this.handleUpdate));
这个.emitter.subscribe(…);
但订阅失败,出现以下错误:
addHandler不是一个函数
错误正如预期的那样,您正在调用
addHandler
和removeHandler
,然后将它们的结果作为参数传递(即不是函数)。按原样传递对函数的引用,然后subscribe
的第一个参数应该是handleUpdateValueForCharacteristic
函数。谢谢,我已经接近了。这个现在很好用。
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);
}
}
private addHandler:Function = (handler:NodeEventHandler):any => {
this.handlerUpdate = bleManagerEmitter.addListener('BleManagerDidUpdateValueForCharacteristic', handler);
return this.handlerUpdate;
}
private removeHandler:Function = (handler:EmitterSubscription, _signal?:any) => {
handler.remove();
}
this.emitter = fromEventPattern<any>(this.addHandler(this.handleUpdateValueForCharacteristic), this.removeHandler(this.handlerUpdate));
this.emitter.subscribe(...);