2

I'm trying to filter native events in React Native with RxJS. I'm using react-native-ble-manager which exposes an EventEmitter. Basically, without RxJS I'm doing the following (only the relevant code is shown here):

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);
       }
    }

Once I'm connected to my BLE peripheral and I've started data retrieval, the arrow function handleUpdateValueForCharacteristic is called with data. That's working fine.

Now I'd like to use RxJS to filter events, because I could receive up to 200 events per second but I'm only interested in 1/4 of them.

I just can't wrap my head around fromEventPattern usage.

What I've tried so far is the following:

Added some handler function in the class:

  private addHandler:Function = (handler:NodeEventHandler):any => {
    this.handlerUpdate = bleManagerEmitter.addListener('BleManagerDidUpdateValueForCharacteristic', handler);
    return this.handlerUpdate;
  }

  private removeHandler:Function = (handler:EmitterSubscription, _signal?:any) => {
    handler.remove();
  }

In componentDidMount():

this.emitter = fromEventPattern<any>(this.addHandler(this.handleUpdateValueForCharacteristic), this.removeHandler(this.handlerUpdate));
this.emitter.subscribe(...);

But subscribe fails with the following error:

addHandler is not a function.

4

0 回答 0