When building our apps with React Native, we often want them to be cross-platform. And the platforms we usually target are Android and iOS. Let’s check the differences between these two!
RCTDeviceEventEmitter which can be obtained from the
ReactContext by using
.getJSModule() method. When you have
RCTDeviceEventEmitter instance you can invoke
emit(String eventName, WritableMap parameters) method on it.
addListener method called on
Here’s where it gets a bit more complicated. You can’t get the instance of
EventEmitter and use it to send a message as easily as it is on Android. You need to subclass
RCTEventEmitter and then implement
supportedEvents method that should return an array of supported events. After that, you’ll be able to use
self sendEventWithName.That boils down to:
3. Send the event using
4. One more thing. You will get a warning notice if you emit an event while there are no listeners. The easiest way to optimize your module and avoid this warning is to override
stopObservingmethods where you set flag
hasListeners and send events only when it is
NativeEventEmitter instance in your module.
It’s really important to unsubscribe your listeners once they’re not needed anymore or you’ll end up leaking memory. Don’t forget that!
Note that you can create more than one module with the event emitter in iOS. To do that, you need to create the specified amount of
This is the difference between iOS and Android but if you have just one module with event emitter, you can simplify it by creating something like this:
You have now one file with the emitter for both platforms. It will work only if you have one module with the event emitter, though.
I hope that I’ve managed to help you understand how to implement and use events in your native module and that now you’ll be able to do it yourself.
Thank you for your time!