Reputation: 97
I went through official documentation of the React Native Headless JS. In the caveats, It is mentioned that if the app will try to run the task in foreground, the app will crash.It is also mentioned that there is a way around this.Please suggest a way so that I can have heavy tasks done in an another thread other than the UI thread using Headless JS when the app is in the foreground.
Upvotes: 4
Views: 3869
Reputation: 714
It worked for me to use the HeadlessJsTaskService
, even when started from a currently active Activity. Did you try it and it crashed?
Edit
I had a look at their implementation. Your app will crash under the following conditions:
if (reactContext.getLifecycleState() == LifecycleState.RESUMED &&
!taskConfig.isAllowedInForeground()) { //crash }
(see ReactContext)
This means that you can configure the HeadlessJsTaskConfig
within your HeadlessJsTaskService
with a true
for allowedInForeground
.
E.g.
@Override
@Nullable
protected HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
WritableMap data = extras != null ? Arguments.fromBundle(extras) : null;
return new HeadlessJsTaskConfig(
"FeatureExecutor",
data,
5000,
true /* Don't crash when running in foreground */);
}
But in my test-case this step was not necessary, even when displaying a ReactRootView. I think the reason for that is, that the ReactRootView had its own ReactContext (which might not be a good idea).
For your implementation you should consider the following when using Headless JS:
allowedInForeground whether to allow this task to run while the app is in the foreground (i.e. there is a host in resumed mode for the current ReactContext). Only set this to true if you really need it. Note that tasks run in the same JS thread as UI code, so doing expensiveoperations would degrade user experience.
(see HeadlessJsTaskConfig.java)
Upvotes: 4