Giter VIP home page Giter VIP logo

react-native-workers's Introduction

react-native-workers

Spin worker threads and run CPU intensive tasks in the background. Bonus point on Android you can keep a worker alive even when a user quit the application ๐ŸŽ†

Features

  • JS web workers for iOS and Android
  • access to native modules (network, geolocation, storage ...)
  • Android Services in JS ๐ŸŽ‰

Installation

npm install react-native-workers --save

Automatic setup

simply rnpm link react-native-workers and you'r good to go.

Manual setup

iOS

  1. Open your project in XCode, right click on Libraries and click Add Files to "Your Project Name". Look under node_modules/react-native-workers/ios and add Workers.xcodeproj
  2. Add libWorkers.a to Build Phases -> Link Binary With Libraries

Android

in android/settings.gradle

 include ':app', ':react-native-workers'
 project(':react-native-workers').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-workers/android')

in android/app/build.gradle add:

dependencies {
   ...
   compile project(':react-native-workers')
}

and finally, in your MainApplication.java add:

import co.apptailor.Worker.WorkerPackage; // <--- This!

public class MainApplication extends Application implements ReactApplication {

private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    protected boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new WorkerPackage() // <--- and this
      );
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
      return mReactNativeHost;
  }
}

Note: only the official react native modules are available from your workers (vibration, fetch, etc...). To include additional modules in your workers add them to the WorkerPackage constructor. Like this:

new WorkerPackage(new MyAwesomePackage(), new MyAmazingPackage())`

JS API

From your application:

import { Worker } from 'react-native-workers';

/* start worker */
const worker = new Worker("path/to/worker.js");

/* post message to worker. String only ! */
worker.postMessage("hello from application");

/* get message from worker. String only ! */
worker.onmessage = (message) => {

}

/* stop worker */
worker.terminate();

From your worker js file:

import { self } from 'react-native-workers';

/* get message from application. String only ! */
self.onmessage = (message) => {
}

/* post message to application. String only ! */
self.postMessage("hello from worker");

Lifecycle

  • the workers are paused when the app enters in the background
  • the workers are resumed once the app is running in the foreground
  • During development, when you reload the main JS bundle (shake device -> Reload) the workers are killed

Todo

  • Android - download worker files from same location as main bundle
  • iOS - download worker files from same location as main bundle
  • script to package worker files for release build
  • load worker files from disk if not debug

react-native-workers's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-workers's Issues

Services in update to RN 0.30

Are you planning to update Android Services for RN 0.30? If so, when it will be ready? I need this module so I started to work on it, any tips are welcome;)

Keeping workers alive while navigating through scenes.

@devfd ,
I am using the worker for image upload, but when I navigate away from that scene, I loose the pointer to that worker in that case I won't be able to terminate it, this can result to memory leak. How can I keep a central worker manager.
What I have done now is to keep it outside the scenes on the Navigation file, and pass it as props into other routes/scenes, but this is not working. Its not throwing any error, and not working either.

Can I schedule task using this package?

I am looking for a package that enables me to shcedule daily or hourly operations and be confident that those are not going to be shut down by the OS, at least in normal battery and resource condition. Extreme cases are not necessary yet (for those I guess server backup is mandatory).

As a fact I posted a question about this on stackoverflow. I am trying th package now but I would ike to know the authors' opinion.

I am trying also with https://www.npmjs.com/package/react-native-background-timer, but since I need to run also services, an Android Service / Web Worker sounds ideal.

Using third party native modules

I am trying to implement local discovery on my react native application for that I use react-native-tcp and react-native-udp.

The problem is the only packages available on the worker are

{
  NetInfo: [Getter],
  WorkerSelfManager: [Getter],
  JSCHeapCapture: [Getter],
  AndroidConstants: [Getter],
  IntentAndroid: [Getter],
  AsyncSQLiteDBStorage: [Getter],
  Vibration: [Getter],
  LocationObserver: [Getter],
  Networking: [Getter],
  SourceCode: [Getter],
  ExceptionsManager: [Getter],
  WebSocketModule:
   { ping: { [Function: fn] type: 'remote' },
     sendBinary: { [Function: fn] type: 'remote' },
     connect: { [Function: fn] type: 'remote' },
     send: { [Function: fn] type: 'remote' },
     close: { [Function: fn] type: 'remote' } },
  Timing:
   { deleteTimer: { [Function: fn] type: 'remote' },
     createTimer: { [Function: fn] type: 'remote' } },
  UIManager: { moduleID: 0, takeSnapshot: [Function] } }
}

The packages I have on the getPackages are the following

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new TcpSocketsModule(),
          new UdpSocketsModule(),
          new WorkerPackage(),
          new VectorIconsPackage()
      );
    }

Keep worker going in background?

In the readme for lifecycle:

the workers are paused when the app enters in the background

In the description it's:

Bonus point on Android you can keep a worker alive even when a user quit the application ๐ŸŽ†

How should I keep it from pausing?

unable to run sample Application

I followed the process given with tutorial ,but gettting following error

\node_modules\react-native-workers\android\src\main\java\co\apptailor\Worker\WorkerModule.java:180: error: cannot find symbol
return JSBundleLoader.createFileLoader(getReactApplicationContext(), "assets://workers/" + jsFileSlug + ".bundle");

Not working with RN version 0.40

/Users/vinay/git/sighte/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:7: error: cannot find symbol import com.facebook.react.bridge.CatalystInstanceImpl; ^ symbol: class CatalystInstanceImpl location: package com.facebook.react.bridge /Users/vinay/git/sighte/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:8: error: cannot find symbol import com.facebook.react.bridge.JSBundleLoader; ^ symbol: class JSBundleLoader location: package com.facebook.react.bridge /Users/vinay/git/sighte/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:9: error: cannot find symbol import com.facebook.react.bridge.JSCJavaScriptExecutor; ^ symbol: class JSCJavaScriptExecutor location: package com.facebook.react.bridge /Users/vinay/git/sighte/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:10: error: cannot find symbol import com.facebook.react.bridge.JavaScriptExecutor; ^ symbol: class JavaScriptExecutor location: package com.facebook.react.bridge /Users/vinay/git/sighte/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:15: error: cannot find symbol import com.facebook.react.bridge.NativeModuleRegistry; ^ symbol: class NativeModuleRegistry location: package com.facebook.react.bridge /Users/vinay/git/sighte/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:28: error: cannot find symbol private JSBundleLoader jsBundleLoader; ^ symbol: class JSBundleLoader location: class ReactContextBuilder /Users/vinay/git/sighte/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:37: error: cannot find symbol public ReactContextBuilder setJSBundleLoader(JSBundleLoader jsBundleLoader) { ^ symbol: class JSBundleLoader location: class ReactContextBuilder /Users/vinay/git/sighte/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:137: error: package NativeModuleRegistry does not exist private void addNativeModules(ReactApplicationContext reactContext, NativeModuleRegistry.Builder nativeRegistryBuilder) { ^ /Users/vinay/git/sighte/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/WorkerModule.java:10: error: cannot find symbol import com.facebook.react.bridge.JSBundleLoader; ^ symbol: class JSBundleLoader location: package com.facebook.react.bridge /Users/vinay/git/sighte/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/WorkerModule.java:168: error: cannot find symbol private JSBundleLoader createDevBundleLoader(String jsFileName, String jsFileSlug) { ^ symbol: class JSBundleLoader location: class WorkerModule /Users/vinay/git/sighte/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/WorkerModule.java:178: error: cannot find symbol private JSBundleLoader createReleaseBundleLoader(String jsFileName, String jsFileSlug) { ^ symbol: class JSBundleLoader location: class WorkerModule /Users/vinay/git/sighte/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:53: error: cannot find symbol JavaScriptExecutor jsExecutor = new JSCJavaScriptExecutor.Factory().create(new WritableNativeMap()); ^ symbol: class JavaScriptExecutor location: class ReactContextBuilder /Users/vinay/git/sighte/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:53: error: package JSCJavaScriptExecutor does not exist JavaScriptExecutor jsExecutor = new JSCJavaScriptExecutor.Factory().create(new WritableNativeMap()); ^ /Users/vinay/git/sighte/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:62: error: package NativeModuleRegistry does not exist NativeModuleRegistry.Builder nativeRegistryBuilder = new NativeModuleRegistry.Builder(); ^ /Users/vinay/git/sighte/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:62: error: package NativeModuleRegistry does not exist NativeModuleRegistry.Builder nativeRegistryBuilder = new NativeModuleRegistry.Builder(); ^ /Users/vinay/git/sighte/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:69: error: package CatalystInstanceImpl does not exist CatalystInstanceImpl.Builder catalystInstanceBuilder = new CatalystInstanceImpl.Builder() ^

Package.java:11: error: cannot find symbol

How to resolve these errors?

C:\Users\CR-27\creatise\test1\node_modules\react-native-workers\android\src\main\java\co\apptailor\Worker\core\BaseReactPackage.java:11: error: cannot find symbol
import com.facebook.react.modules.core.JSTimersExecution;
^
symbol: class JSTimersExecution
location: package com.facebook.react.modules.core
C:\Users\CR-27\creatise\test1\node_modules\react-native-workers\android\src\main\java\co\apptailor\Worker\core\ReactContextBuilder.java:9: error: JSCJavaScriptExecutor is not public in com.facebook.react.bridge; cannot be accessed from outside package
import com.facebook.react.bridge.JSCJavaScriptExecutor;
^
C:\Users\CR-27\creatise\test1\node_modules\react-native-workers\android\src\main\java\co\apptailor\Worker\core\ReactContextBuilder.java:19: error: cannot find symbol
import com.facebook.react.devsupport.DevSupportManager;
^
symbol: class DevSupportManager
location: package com.facebook.react.devsupport
C:\Users\CR-27\creatise\test1\node_modules\react-native-workers\android\src\main\java\co\apptailor\Worker\core\ReactContextBuilder.java:29: error: cannot find symbol
private DevSupportManager devSupportManager;
^
symbol: class DevSupportManager
location: class ReactContextBuilder
C:\Users\CR-27\creatise\test1\node_modules\react-native-workers\android\src\main\java\co\apptailor\Worker\core\ReactContextBuilder.java:42: error: cannot find symbol
public ReactContextBuilder setDevSupportManager(DevSupportManager devSupportManager) {
^
symbol: class DevSupportManager
location: class ReactContextBuilder
C:\Users\CR-27\creatise\test1\node_modules\react-native-workers\android\src\main\java\co\apptailor\Worker\core\ReactContextBuilder.java:128: error: cannot find symbol

Worker not working with hot reloading

When trying to run my app with hot reloading, the worker does not work properly. I get the following messages:

2016-11-17 21:16:21.277 app[15089:2120623] No parent bridge defined - abord sending worker message

If I disable hot reloading, things work fine but I don't get access to the dev menu anymore once the worker has started.

Compile error: cannot find symbol

Compiling my project on android throws me errors.
I get 11 errors in android studios formulated similarily: error: cannot find symbol <...> :
skarmavbild 2018-12-05 kl 13 35 20
and when running in terminal:

> Task :react-native-workers:compileDebugJavaWithJavac FAILED
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/BaseReactPackage.java:11: error: cannot find symbol
import com.facebook.react.modules.core.JSTimersExecution;
                                      ^
  symbol:   class JSTimersExecution
  location: package com.facebook.react.modules.core
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:9: error: JSCJavaScriptExecutor is not public in com.facebook.react.bridge; cannot be accessed from outside package
import com.facebook.react.bridge.JSCJavaScriptExecutor;
                                ^
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:19: error: cannot find symbol
import com.facebook.react.devsupport.DevSupportManager;
                                    ^
  symbol:   class DevSupportManager
  location: package com.facebook.react.devsupport
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:29: error: cannot find symbol
    private DevSupportManager devSupportManager;
            ^
  symbol:   class DevSupportManager
  location: class ReactContextBuilder
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:42: error: cannot find symbol
    public ReactContextBuilder setDevSupportManager(DevSupportManager devSupportManager) {
                                                    ^
  symbol:   class DevSupportManager
  location: class ReactContextBuilder
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:128: error: cannot find symbol
    private void addJSModules(JavaScriptModuleRegistry.Builder jsModulesBuilder) {
                                                      ^
  symbol:   class Builder
  location: class JavaScriptModuleRegistry
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:137: error: cannot find symbol
    private void addNativeModules(ReactApplicationContext reactContext, NativeModuleRegistry.Builder nativeRegistryBuilder) {
                                                                                            ^
  symbol:   class Builder
  location: class NativeModuleRegistry
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/WorkerModule.java:16: error: cannot find symbol
import com.facebook.react.devsupport.DevSupportManager;
                                    ^
  symbol:   class DevSupportManager
  location: package com.facebook.react.devsupport
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/WorkerModule.java:188: error: cannot find symbol
    private DevSupportManager getDevSupportManager() {
            ^
  symbol:   class DevSupportManager
  location: class WorkerModule
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/BaseReactPackage.java:42: error: constructor AndroidInfoModule in class AndroidInfoModule cannot be applied to given types;
                new AndroidInfoModule(),
                ^
  required: ReactApplicationContext
  found: no arguments
  reason: actual and formal argument lists differ in length
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/BaseReactPackage.java:46: error: cannot find symbol
                new SourceCodeModule(reactInstanceManager.getSourceUrl()),
                                                         ^
  symbol:   method getSourceUrl()
  location: variable reactInstanceManager of type ReactInstanceManager
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/BaseReactPackage.java:61: error: method does not override or implement a method from a supertype
    @Override
    ^
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/BaseReactPackage.java:65: error: cannot find symbol
                JSTimersExecution.class,
                ^
  symbol:   class JSTimersExecution
  location: class BaseReactPackage
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:53: error: package JSCJavaScriptExecutor does not exist
        JavaScriptExecutor jsExecutor = new JSCJavaScriptExecutor.Factory().create(new WritableNativeMap());
                                                                 ^
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:62: error: cannot find symbol
        NativeModuleRegistry.Builder nativeRegistryBuilder = new NativeModuleRegistry.Builder();
                            ^
  symbol:   class Builder
  location: class NativeModuleRegistry
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:62: error: cannot find symbol
        NativeModuleRegistry.Builder nativeRegistryBuilder = new NativeModuleRegistry.Builder();
                                                                                     ^
  symbol:   class Builder
  location: class NativeModuleRegistry
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:66: error: cannot find symbol
        JavaScriptModuleRegistry.Builder jsModulesBuilder = new JavaScriptModuleRegistry.Builder();
                                ^
  symbol:   class Builder
  location: class JavaScriptModuleRegistry
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:66: error: cannot find symbol
        JavaScriptModuleRegistry.Builder jsModulesBuilder = new JavaScriptModuleRegistry.Builder();
                                                                                        ^
  symbol:   class Builder
  location: class JavaScriptModuleRegistry
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/core/ReactContextBuilder.java:131: error: cannot find symbol
            for (Class<? extends JavaScriptModule> jsModuleClass : reactPackage.createJSModules()) {
                                                                               ^
  symbol:   method createJSModules()
  location: variable reactPackage of type ReactPackage
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/WorkerModule.java:180: error: no suitable method found for createFileLoader(ReactApplicationContext,String)
        return JSBundleLoader.createFileLoader(getReactApplicationContext(), "assets://workers/" + jsFileSlug + ".bundle");
                             ^
    method JSBundleLoader.createFileLoader(String) is not applicable
      (actual and formal argument lists differ in length)
    method JSBundleLoader.createFileLoader(String,String,boolean) is not applicable
      (actual and formal argument lists differ in length)
/Users/admin/Documents/Local/Parking-app/node_modules/react-native-workers/android/src/main/java/co/apptailor/Worker/WorkerPackage.java:21: error: method does not override or implement a method from a supertype
    @Override
    ^
21 errors


FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-workers:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 8s
93 actionable tasks: 75 executed, 18 up-to-date
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/getting-started.html

"dependencies": {
"axios": "^0.18.0",
"geolib": "^2.0.24",
"lottie-react-native": "^2.5.9",
"react": "16.4.1",
"react-native": "0.56.1",
"react-native-cli": "^2.0.1",
"react-native-push-notification": "^3.1.1",
"react-native-sortable-listview": "^0.2.8",
"react-native-svg": "^0.7.2", //Former 0.7.2
"react-native-workers": "^0.3.1",
"react-navigation": "^2.16.0"
},
node version: v8.11.4

I had the same problem with react-native-svg and solved it by clearing node_modules and re installing again.
software-mansion/react-native-svg#866 (comment)
But it got me this error instead.

Enable semantics similar to `java.lang.Thread`?

I've been having ridiculous problems with trying to get this to work in a non-headachy way, not through any fault of your own. This is a great library and I appreciate your work! But I'm using ClojureScript (a compile-to-JS language) and due to its fancy use of Google Closure and other such things, I'm not able to get Workers to work in an easy way (I can use them on the web just fine with ClojureScript). I'd love to have this library support (in addition to the existing WebWorkers semantics, because I suppose some people want that) java.lang.Thread-esque semantics like this:

var fnICanRunOnAnyThread = function () {
  if (Thread.isMainThread) {
    console.log("Hello world from main thread!");
    console.log("I can also do UI things!");
    ReactNative.WhateverComponent.whateverUIFunctionWorkersCantCallWithoutError();
  } else {
    console.log("Hello world from worker (non-main) thread!");
    console.log("I can't do UI things but that's okay cause these semantics are awesome!");
  }
}

var myFn = function () {
  new Thread(fnICanRunOnAnyThread);
}

I'm thinking that under the hood Thread might use the native bridge to spin up a JS VM and load all the JS code that the current context has access to (yes, this part would be hard), and then inject a boolean Thread.isMainThread = true (I'm not sure if this is possible but it if it is, it seems like it would be simple and it would be dang nice).

Thoughts on feasibility?
I'd love to contribute to help make this possible.

Documentation for running in release/production?

I tried running a production version (Scheme -> Build Configuration = Release), the main bundle loads and attempts to start the worker, but this just repeats in my logs:

2016-08-03 13:50:35.543 FutureApp[9291:273962] starting Worker file:///Users/sean/Library/Developer/CoreSimulator/Devices/EC847FD2-23EB-4CAA-B10A-87D8F21F55D7/data/Containers/Bundle/Application/A0442033-AC22-4336-9364-1B2F628ADA6F/FutureApp.app/main.jsbundle
2016-08-03 13:50:35.727 FutureApp[9291:274381] starting Worker file:///Users/sean/Library/Developer/CoreSimulator/Devices/EC847FD2-23EB-4CAA-B10A-87D8F21F55D7/data/Containers/Bundle/Application/A0442033-AC22-4336-9364-1B2F628ADA6F/FutureApp.app/main.jsbundle
2016-08-03 13:50:35.887 FutureApp[9291:273962] starting Worker file:///Users/sean/Library/Developer/CoreSimulator/Devices/EC847FD2-23EB-4CAA-B10A-87D8F21F55D7/data/Containers/Bundle/Application/A0442033-AC22-4336-9364-
......

I added the worker.js file to my project folder and can confirm it's being copied to the same folder. But it looks like the worker is trying to load the wrong file? The main.jsbundle file is the output of the react native packager, right?

iOS linking cause some odd XCode compile issues

Running: react-native link react-native-workers

And then trying to open the project with xcode (i.e, to manually link another library), breaks the project in a way it can no longer compile.

Basically, it causes some React modules to fail to compile.

Running unlink reverts the issue.

Errors:

screen shot 2018-07-28 at 21 22 20

screen shot 2018-07-28 at 21 22 48

screen shot 2018-07-28 at 21 23 11

Forgot to mention: React Native 0.56.0

Looks like some change after react 0.40 broke this with the imports.

Simple example?

Trying to picture using this but, not sure where the "worker" lives. For example, how would I poll an endpoint in the work and send that data to the app?

A problem occurred configuring project ':app'. > Could not resolve all dependencies for configuration ':app:_debugApk'. > A problem occurred configuring project ':react-native-workers'. > The SDK Build Tools revision (23.0.1) is too low for project ':react-native-workers'. Minimum required is 25.0.0

and my RN version is
{
"name": "test1",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"native-base": "^2.7.2",
"react": "16.4.1",
"react-native": "0.55.2",
"react-native-clean-form": "^0.5.0",
"react-native-cookies": "^3.3.0",
"react-native-easy-grid": "^0.2.0",
"react-native-image-crop-picker": "^0.20.3",
"react-native-workers": "^0.3.1",
"react-navigation": "^2.9.3"
},
"devDependencies": {
"babel-jest": "23.4.0",
"babel-preset-react-native": "4.0.0",
"jest": "23.4.1",
"react-test-renderer": "16.4.1"
},
"jest": {
"preset": "react-native"
}
}

error ;

FAILURE: Build failed with an exception.

  • What went wrong:
    A problem occurred configuring project ':app'.

Could not resolve all dependencies for configuration ':app:_debugApk'.
A problem occurred configuring project ':react-native-workers'.
> The SDK Build Tools revision (23.0.1) is too low for project ':react-native-workers'. Minimum required is 25.0.0

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 8.979 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/getting-started.html

postMessage is not working

postMessage method is not working from parent file. Worker.js is not receiving onmessage event

Parent script

const worker = new Worker('src/containers/worker.js');
            worker.onmessage = (message)=>{
                console.log('asfasfafasfsafa')
            }
            worker.postMessage("start");

Worker script

import { self } from 'react-native-workers';

/* get message from application. String only ! */


self.onmessage = (message) => {
    console.log('i m worker' + message);
}

/* post message to application. String only ! */
self.postMessage("hello from worker");

Does this not work with Chrome debugging?

So I've got the example up and running, but it crashes if I enable Remote JS Debugging:

2016-08-01 17:00:33.792 WorkerSampleApp[3333:62924] starting Worker http://localhost:8081/simple-worker.bundle?platform=ios&dev=true&minify=false
2016-08-01 17:00:33.934 [info][tid:NSOperationQueue 0x7f9633f18bd0 :: NSOperation 0x7f9633c1d220 (QOS: LEGACY)][RCTPerformanceLogger.m:41] Unbalanced calls start/end for tag 0
2016-08-01 17:00:35.791 [fatal][tid:com.facebook.react.WebSocketExecutor] Runtime is not ready for debugging. Make sure Packager server is running.
2016-08-01 17:00:35.830 [error][tid:com.facebook.react.RCTBridgeQueue][RCTWebSocketExecutor.m:78] Connection to http://localhost:8081/debugger-proxy?role=client timed out. Are you running node proxy? If you are running on the device, check if you have the right IP address in `RCTWebSocketExecutor.m`.
2016-08-01 17:00:35.830 [info][tid:com.facebook.react.RCTBridgeQueue][RCTPerformanceLogger.m:41] Unbalanced calls start/end for tag 14
2016-08-01 17:00:39.144 WorkerSampleApp[3333:63042] No parent bridge defined - abord sending worker message
2016-08-01 17:00:44.161 WorkerSampleApp[3333:63041] No parent bridge defined - abord sending worker message
2016-08-01 17:00:49.176 WorkerSampleApp[3333:63041] No parent bridge defined - abord sending worker message

The last message repeats every 5 seconds which makes me think the worker has loaded, but the messages just aren't getting through.

Any ideas?

React-native-worker not working issue with @Override

HI ,
I am new to react-native i integrated react-native-workers as you mentioned in this repo i tried with manual as well as automatic. i am getting the below errors. i am unable to find any solution to resolve it. Please help me out to solve this problem.

import com.facebook.react.modules.core.JSTimersExecution;
^
symbol: class JSTimersExecution
location: package com.facebook.react.modules.core
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\core\ReactContextBuilder.java:9: error: JSCJav aScriptExecutor is not public in com.facebook.react.bridge; cannot be accessed f rom outside package
import com.facebook.react.bridge.JSCJavaScriptExecutor;
^
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\core\ReactContextBuilder.java:19: error: canno t find symbol
import com.facebook.react.devsupport.DevSupportManager;
^
symbol: class DevSupportManager
location: package com.facebook.react.devsupport
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\core\ReactContextBuilder.java:29: error: canno t find symbol
private DevSupportManager devSupportManager;
^
symbol: class DevSupportManager
location: class ReactContextBuilder
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\core\ReactContextBuilder.java:42: error: canno t find symbol
public ReactContextBuilder setDevSupportManager(DevSupportManager devSupport Manager) {
^
symbol: class DevSupportManager
location: class ReactContextBuilder
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\core\ReactContextBuilder.java:128: error: cann ot find symbol
private void addJSModules(JavaScriptModuleRegistry.Builder jsModulesBuilder) {
^
symbol: class Builder
location: class JavaScriptModuleRegistry
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\core\ReactContextBuilder.java:137: error: cann ot find symbol
private void addNativeModules(ReactApplicationContext reactContext, NativeMo duleRegistry.Builder nativeRegistryBuilder) {
^
symbol: class Builder
location: class NativeModuleRegistry
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\WorkerModule.java:16: error: cannot find symbo l
import com.facebook.react.devsupport.DevSupportManager;
^
symbol: class DevSupportManager
location: package com.facebook.react.devsupport
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\WorkerModule.java:188: error: cannot find symb ol
private DevSupportManager getDevSupportManager() {
^
symbol: class DevSupportManager
location: class WorkerModule
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\core\BaseReactPackage.java:46: error: cannot f ind symbol
new SourceCodeModule(reactInstanceManager.getSourceUrl()),
^
symbol: method getSourceUrl()
location: variable reactInstanceManager of type ReactInstanceManager
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\core\BaseReactPackage.java:61: error: method d oes not override or implement a method from a supertype
@OverRide
^
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\core\BaseReactPackage.java:65: error: cannot f ind symbol
JSTimersExecution.class,
^
symbol: class JSTimersExecution
location: class BaseReactPackage
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\core\ReactContextBuilder.java:53: error: packa ge JSCJavaScriptExecutor does not exist
JavaScriptExecutor jsExecutor = new JSCJavaScriptExecutor.Factory().crea te(new WritableNativeMap());
^
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\core\ReactContextBuilder.java:62: error: canno t find symbol
NativeModuleRegistry.Builder nativeRegistryBuilder = new NativeModuleReg istry.Builder();
^
symbol: class Builder
location: class NativeModuleRegistry
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\core\ReactContextBuilder.java:62: error: canno t find symbol
NativeModuleRegistry.Builder nativeRegistryBuilder = new NativeModuleReg istry.Builder();
^
symbol: class Builder
location: class NativeModuleRegistry
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\core\ReactContextBuilder.java:66: error: canno t find symbol
JavaScriptModuleRegistry.Builder jsModulesBuilder = new JavaScriptModule Registry.Builder();
^
symbol: class Builder
location: class JavaScriptModuleRegistry
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\core\ReactContextBuilder.java:66: error: canno t find symbol
JavaScriptModuleRegistry.Builder jsModulesBuilder = new JavaScriptModule Registry.Builder();
^
symbol: class Builder
location: class JavaScriptModuleRegistry
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\core\ReactContextBuilder.java:131: error: cann ot find symbol
for (Class<? extends JavaScriptModule> jsModuleClass : reactPackage. createJSModules()) {
^
symbol: method createJSModules()
location: variable reactPackage of type ReactPackage
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\WorkerModule.java:180: error: no suitable meth od found for createFileLoader(ReactApplicationContext,String)
return JSBundleLoader.createFileLoader(getReactApplicationContext(), "as sets://workers/" + jsFileSlug + ".bundle");
^
method JSBundleLoader.createFileLoader(String) is not applicable
(actual and formal argument lists differ in length)
method JSBundleLoader.createFileLoader(String,String,boolean) is not applica ble
(actual and formal argument lists differ in length)
C:\Users\Scketch\Desktop\scketch-chat\node_modules\react-native-workers\android\ src\main\java\co\apptailor\Worker\WorkerPackage.java:21: error: method does not override or implement a method from a supertype
@OverRide
^
20 errors
:react-native-workers:compileReleaseJavaWithJavac FAILED

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':react-native-workers:compileReleaseJavaWithJavac'.

Compilation failed; see the compiler error output for details.

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 1 mins 21.781 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/getting-started.html

Getting Error on the latest version

Hi @devfd , many thanks for the updated version :) I ran into some issues when I try to use the latest version,

I am using RN 0.30.0 on a Ubuntu 14.04.4 machine

Issue #1: RNPM link gives build error, so I went with manual and that worked for me

Issue #2: When I try to use "new Worker()", it throws an error saying that

Attempt to invoke virtual method 'android.app.Activity.getApplication()' on a null object reference'

Here is what I am doing,

I created a worker.js file on the same directory of my container and called the worker as follows,

`import { Worker } from 'react-native-workers';

/* start worker */
const worker = new Worker("./worker.js");`

Here is the content in my worker.js

`import { self } from 'react-native-workers';

/* get message from application. String only ! */
self.onmessage = (message) => {
}

/* post message to application. String only ! */
self.postMessage("hello from worker");`

Am I missing something here?

Error downloading web worker

I have worker script in same folder in which I have a file in which I am worker js.

//service.js
const worker = new Worker('worker.js');

Both service.js and worker.js is in same folder.

screen shot 2016-09-27 at 5 09 29 pm

Background worker is always loading, it doesn't execute.

Using react-native-workers: ^0.3.1,
react-native: ^0.34.1

When i start my worker in componentDidMount. The script gets downloaded, but it doesnt get executed on device.
screen shot 2016-10-11 at 11 16 04 pm

I am using debug mode and Loading from ip.xip.io:port always remains in status bar.

Could observe following in perf monitor.

image

is the repo being maintained?

Tried to install this for RN 0.30.2 but getting build errors for android. Saw that there are other pending issues also.

Run workers on iOS device using offline release bundles

Here is what I had to do to make workers work on iOS using offline release bundles.

  1. Fix node_modules/react-native-workers/ios/Workers/WorkerManager.m as follows:
  //NSURL *workerURL = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:name fallbackResource:nil];
  NSURL *workerURL = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:name fallbackResource:name];
  1. Create a react-native-workers.sh script (see below) inside the ios folder and add it to Build Phases > Bundle React Native code and images:
export NODE_BINARY=node
./react-native-workers.sh
../node_modules/react-native/packager/react-native-xcode.sh

--- ios/react-native-workers.sh ---
Change App/Workers and App/Workers/*Worker.js to match the location and filename pattern of your workers.

#!/bin/bash
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.

# Bundle React Native app's code and image assets.
# This script is supposed to be invoked as part of Xcode build process
# and relies on environment variables (including PWD) set by Xcode

case "$CONFIGURATION" in
  Debug)
    # Speed up build times by skipping the creation of the offline package for debug
    # builds on the simulator since the packager is supposed to be running anyways.
    if [[ "$PLATFORM_NAME" == *simulator ]]; then
      echo "Skipping bundling for Simulator platform"
      exit 0;
    fi

    DEV=true
    ;;
  "")
    echo "$0 must be invoked by Xcode"
    exit 1
    ;;
  *)
    DEV=false
    ;;
esac

# Path to react-native folder inside node_modules
REACT_NATIVE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../node_modules/react-native" && pwd)"

# Xcode project file for React Native apps is located in ios/ subfolder
cd ..

# Define NVM_DIR and source the nvm.sh setup script
[ -z "$NVM_DIR" ] && export NVM_DIR="$HOME/.nvm"

if [[ -s "$HOME/.nvm/nvm.sh" ]]; then
  . "$HOME/.nvm/nvm.sh"
elif [[ -x "$(command -v brew)" && -s "$(brew --prefix nvm)/nvm.sh" ]]; then
  . "$(brew --prefix nvm)/nvm.sh"
fi

# Set up the nodenv node version manager if present
if [[ -x "$HOME/.nodenv/bin/nodenv" ]]; then
  eval "$("$HOME/.nodenv/bin/nodenv" init -)"
fi

[ -z "$NODE_BINARY" ] && export NODE_BINARY="node"

nodejs_not_found()
{
  echo "error: Can't find '$NODE_BINARY' binary to build React Native bundle" >&2
  echo "If you have non-standard nodejs installation, select your project in Xcode," >&2
  echo "find 'Build Phases' - 'Bundle React Native code and images'" >&2
  echo "and change NODE_BINARY to absolute path to your node executable" >&2
  echo "(you can find it by invoking 'which node' in the terminal)" >&2
  exit 2
}

type $NODE_BINARY >/dev/null 2>&1 || nodejs_not_found

# Print commands before executing them (useful for troubleshooting)
set -x

# change App/Workers to match the location of your workers
DEST=$CONFIGURATION_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH/App/Workers
mkdir -p $DEST

# Get list of entry files (change App/Workers/*Worker.js to match the location and filename pattern of your workers)
for ENTRY_FILE in ${1:-App/Workers/*Worker.js}
do

  ENTRY_FILE_BASENAME=$(basename $ENTRY_FILE | cut -d. -f1)
  BUNDLE_FILE="$DEST/$ENTRY_FILE_BASENAME.jsbundle"

  $NODE_BINARY "$REACT_NATIVE_DIR/local-cli/cli.js" bundle \
    --entry-file "$ENTRY_FILE" \
    --platform ios \
    --dev $DEV \
    --reset-cache \
    --bundle-output "$BUNDLE_FILE" \
    --assets-dest "$DEST"

  if [[ ! $DEV && ! -f "$BUNDLE_FILE" ]]; then
    echo "error: File $BUNDLE_FILE does not exist. This must be a bug with" >&2
    echo "React Native, please report it here: https://github.com/facebook/react-native/issues"
    exit 2
  fi

done

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.