How to intercept event in java

vasyl :

I'm working on an app in react native and I implemented a module that sends java event to js so it can be listened in react native.

Is there any way to listen it in another java file?

Here is the example event:

            int score = 10;

            sendEvent("SCORE", score);

The module itself looks as below:

// Called to emit events to event listeners in JS
private void sendEvent(String eventName, int result) {
    getReactApplicationContext()
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
            .emit(eventName, result);

I can read it with listener in js, but have no clue how to read it in another java file.

sorifiend :

The best way to do this is probably to store the result and event name as a java variable, then you can easily access it from elsewhere.

The first thing to do is to make a java variable that will be available from another class (public) and give it a default value to avoid any issues.

//Create Java variables
public static int myValueResult = 0;
public static string myValueName = "";

// Called to emit events to event listeners in JS
private void sendEvent(String eventName, int result) {
getReactApplicationContext()
        //JS Method
        .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
        .emit(eventName, result);

        //Add an extra line that saves the result and eventName to the Java variables we made 
        myValueResult = result;
        myValueName = eventName;
}

Now you can get the result from another Java class like below. Just replace classWithEvent with the real name of the class that contains your sendEvent method:

int resultFromOtherClass_result = classWithEvent.myValueResult;
string resultFromOtherClass_name = classWithEvent.myValueName;

Edit: This event is already doing the listening, so there is no need to listen in another java class. Instead, you can simply call a method in another class, a bit like this, then whenever the sendEvent happens you can do whatever you want with it in that class:

myOtherClass.doEvent(eventName, result);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=107793&siteId=1