Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DeviceEventEmitter vs NativeAppEventEmitter

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?

like image 298
Rubys Avatar asked Apr 18 '16 11:04

Rubys


2 Answers

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

like image 182
雨天海角 Avatar answered Oct 19 '22 07:10

雨天海角


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});
    });                                                                                             
like image 4
Ben Clayton Avatar answered Oct 19 '22 08:10

Ben Clayton