24

I want to use events to communicate between native ios/android and my react native app.

I see two ways to do this: DeviceEventEmitter and NativeAppEventEmitter, which seem to be fairly identical.

What's the difference between them? Why should I pick one over the other?

RK-
  • 12,099
  • 23
  • 89
  • 155
Rubys
  • 3,167
  • 2
  • 25
  • 26

2 Answers2

12

Both DeviceEventEmitterand NativeAppEventEmitter are deprecated, you should use NativeEventEmitter instead.

mech
  • 2,775
  • 5
  • 30
  • 38
雨天海角
  • 121
  • 1
  • 2
  • It's in the source: https://github.com/facebook/react-native/blob/1490ab12ef156bf3201882eeabfcac18a1210352/Libraries/EventEmitter/RCTNativeAppEventEmitter.js#L15 & https://github.com/facebook/react-native/blob/1490ab12ef156bf3201882eeabfcac18a1210352/Libraries/EventEmitter/RCTDeviceEventEmitter.js#L32 – se_bastiaan Apr 18 '18 at 13:32
4

I've found I need to use both when developing cross-platform native extensions that need to send events from Java/Obj-C to JavaScript.

On iOS you send events to JS like this:

[self.bridge.eventDispatcher sendAppEventWithName:@"myProgressEvent" body:@{               
 @"progress": @( (float)loaded / (float)total )
}];

.. which you pick up in JS using NativeAppEventEmitter.

In Java you send events to JS with:

WritableMap map = Arguments.createMap();
map.putDouble("progress", progress);
getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
        .emit("myProgressEvent", map);                                                                                   

.. which you pick up in JS using DeviceEventEmitter

It's not ideal, as your JS code needs to then choose the right emitter for the events to be received.

E.g.

    const emitter = Platform.OS == 'ios' ? NativeAppEventEmitter : DeviceEventEmitter;
    emitter.addListener("myProgressEvent", (e:Event)=>{
        console.log("myProgressEvent " + JSON.stringify(e));
        if (!e) {
            return;
        }
        this.setState({progress: e.progress});
    });                                                                                             
Ben Clayton
  • 80,996
  • 26
  • 120
  • 129
  • 3
    This is no reason to choose one over the other, because it's wrong. Check out iOS's RCTEventDispatcher's sendDeviceEventWithName, and React Native Android's com.facebook.react.modules.core.RCTNativeAppEventEmitter, you can send from both platforms to both event emitters. – Rubys Apr 30 '16 at 11:40