Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Android React Native ReactRootView use Activity or Application context?

In the React Native documentation for integrating with Android, it includes this snippet for integrating with Android:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mReactRootView = new ReactRootView(this);
    mReactInstanceManager = ReactInstanceManager.builder()
            .setApplication(getApplication())
            .setBundleAssetName("index.android.bundle")
            .setJSMainModulePath("index")
            .addPackage(new MainReactPackage())
            .setUseDeveloperSupport(BuildConfig.DEBUG)
            .setInitialLifecycleState(LifecycleState.RESUMED)
            .build();
    mReactRootView.startReactApplication(mReactInstanceManager, "MyReactNativeApp", null);

    setContentView(mReactRootView);
}

However, when I use this as-is I get a 100% repro memory leak caused by a ThemedReactContext holding a reference to the ReactRootView which holds a reference to my custom activity.

This is because the Context argument passed to the constructor of ReactRootView is this, which is a reference to my custom activity.

Instead, if I do:

mReactRootView = new ReactRootView(getApplication());

I get no memory leaks.

Is it safe to change the source of my context for a new ReactRootView, and is this a bug that should either a) be fixed or b) should see the documentation changed?

like image 753
esilver Avatar asked Oct 08 '17 17:10

esilver


1 Answers

It looks like the context is only used to initialize the FrameLayout. Technically passing in an application context will work to avoid the memory leak, however the styling might be messed up since "the inflation will be done with the default theme for the system in which you are running, not what's defined in your application."

See this article on different context capabilities.

like image 74
Steve Strates Avatar answered Oct 18 '22 23:10

Steve Strates