React Native: sending events from android to javascript

there is documentation on how to communicate with JavaScript RN parts with native parts in android and ios over the RN bridge. What is unclear is the life cycle for communication with the bridge .

Iu8pj.png

(source medium )

I have a background service in android and I need to send events to my RN application. This is how I send events from my Android Service :

 private RCTDeviceEventEmitter emitter() { return mReactContext.getJSModule(RCTDeviceEventEmitter.class); } private void pushPayload(String event, WritableMap payload) { emitter().emit(event, payload); } public void sendTimerEvent(long remaining) { WritableMap data = Arguments.createMap(); data.putInt("remaining", (int) remaining); pushPayload("timeoutEvent", data); } 

On the javascript side, I use the following static code (not in the component, just the code imported into my index.android.js file:

 const subscribeForNativeEvents = (eventID, callback) => { const Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter; Emitter.addListener(eventID, callback); }; subscribeForNativeEvents('timeoutEvent', (event) => { // work with event.remaining }); 

My service starts even when the application is in the background. But I want to make sure that I'm only trying to contact the javascript side when it is safe.

Sometimes I get errors like React: Calling JS function after bridge has been destroyed . Is there a way to find out whether the modem is available on the native (android) side or not?

It's not about how to save the background code, but rather, to make sure that as long as my own (android) code is running, I can guarantee that the events will not be lost.

+5
source share
1 answer

The problem occurs when the corresponding ReactContext / CatalystInstance has already been destroyed, and you try to do some JS things from the native side (for example, send events, make callbacks, etc.).

I think your best bet is to use lifecycle callbacks, i.e. onHostResume, onHostDestroy ( https://facebook.imtqy.com/react-native/docs/native-modules-android.html#listening-to-lifecycle-events ) or use another callback onCatalystInstanceDestroy ( https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/ReactAndroid/src/main/java/com/facebook/react/bridgeNjMative_bativeNb

Send events only when you know that they are not destroyed.

The main idea is that usually the reaction context is tied to a specific Activity / Context in your application, and you can know this life cycle through callbacks in the NativeModule.

You can find more information ( https://github.com/facebook/react-native/blob/b531612b2c917e1f2bd6bb37bf854fe51e658b36/ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java#L104

+1
source

Source: https://habr.com/ru/post/1276009/


All Articles