2

Is it possible to maintain the value of Java variables in a custom react native module when reloading the JS? I would like to maintain components in the below code for debugging purposes. It persists on onHostResume if the app goes into the background but on reload the value is lost.

public class CustomModule extends ReactContextBaseJavaModuleWithEvents implements LifecycleEventListener {

    public List<JsonObject> components = new ArrayList<>();

    public CustomModule(ReactApplicationContext reactContext) {
        super(reactContext);
        reactContext.addLifecycleEventListener(this);
    }

    @ReactMethod
    void addComponents(component) {
        // add some components...
        components.add(component);
    }

    @Override
    public String getName() {
        return "CustomModule";
    }

    @Override
    public void onHostResume() {
        getReactApplicationContext()
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
            .emit("DEBUG_TAG", components.toString());
    }

}
5
  • The method of storing variables using local storage looks good. Commented Jul 18, 2019 at 2:30
  • I reversed the edit as I’m not using Expo at all for my app and this is part of a custom native module which is why I added the current tags Commented Jul 18, 2019 at 5:57
  • In the case of the Expo, the React-native is used equally. The more tags involved, the more your expert in the field will see your question. Commented Jul 18, 2019 at 6:14
  • My answer to your question is using local storage. Commented Jul 18, 2019 at 6:36
  • Thanks but I resolved the issue. I should have set the List as a static class variable so that it is only initialized once rather than initialized every time on reload. Commented Jul 18, 2019 at 19:11

1 Answer 1

0

Every reload the JS code is creating a new instance of CustomModule reinitializing components. I should have set the components List as a static class variable so that it is only initialized once.

public class CustomModule extends ReactContextBaseJavaModuleWithEvents implements LifecycleEventListener {

    public static List<JsonObject> components = new ArrayList<>();

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.