代码之家  ›  专栏  ›  技术社区  ›  Olivier MATROT

RxJS fromEventPattern与React本机事件

  •  1
  • Olivier MATROT  · 技术社区  · 7 年前

    我试图在React native with RxJS中过滤本机事件。我使用的是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不是函数。

    0 回复  |  直到 7 年前
    推荐文章