Where I work we are attempting to use react native in a slightly non standard way. We would not like to use it for views but instead just use it for its ability to run java code to allow us to create all of our business logic in js and front ends for Android iOS and Web using Java, Swift/Objective-c, and Javascript respectively.
We are doing something like this in iOS:
NSURL *bundleURL = ...;
RCTBridgeModuleProviderBlock block = nil;
NSDictionary *launchOptions = nil;
RCTBridge *bridge = [[RCTBridge alloc] initWithBundleURL:bundleURL moduleProvider:block launchOptions:nil];
Our iOS developer is able to create a RCTBridge that he then uses to communicate with the JS code from objective-c. He is planning to hold onto that bridge for the life of the app. I can't find something similar on Android/Java. I did get ReactInstanceManager working like below:
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModuleName("index.android")
.addPackage(new MainReactPackage())
.addPackage( searchPackage )
.setUseDeveloperSupport( BuildConfig.DEBUG )
.setInitialLifecycleState( LifecycleState.RESUMED)
.build();
mReactInstanceManager.createReactContextInBackground();
The annoying part about wiring things up with ReactInstanceManager is that it requires some lifecycle callbacks which kinda makes it tied to a specific activity. I want to do what iOS is doing and create a bridge and keep that instance for the whole app across multiple different activities.
So is there something similar to the RCTBridge that exists in iOS? If not then is there a reason I should not share the same reactInstanceManager across multiple activities?
The docs state your can keep the ReactInstanceManager as a singleton and use it across multiple activities as long as you wire it to the activities life cycle methods.
I found one issue with this approach though. On Android, if your activities extend the base ReactNative activity, the ReactInstanceManager
gets destroyed when onDestroy()
is called.
So if you open a second activity from your MainActivity
- once returning to your MainActivity
, mReactInstanceManager
is nullified and your singleton is basically worthless.
I've opened an issue about this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With