README.md 5.39 KB
Newer Older
1
# react-native-threads
2

3 4 5 6 7 8 9 10 11
Spawn new react native JavaScript processes for CPU intensive work outside of your
main UI JavaScript process.

Despite this package's name, this isn't real 'threading', but rather multi-processing.
The main tradeoff of using this library is memory usage, as creating new JS processes
can have significant overhead.  Be sure to benchmark your app's memory usage and other
resources before using this library! Alternative solutions include using `runAfterInteractions`
or the [Interaction Manager](https://facebook.github.io/react-native/docs/interactionmanager.html),
and I recommend you investigate those thoroughly before using this library.
12 13 14 15 16 17 18 19 20

## Getting started

`$ npm install react-native-thread --save`

### Mostly automatic installation

`$ react-native link react-native-thread`

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
### Android

For android you will need to make a slight modification to your `MainApplication.java`
file.  In the `getPackages` method pass in `mReactNativeHost` to the `RNThreadPackage`
constructor:

```java
    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
        new MainReactPackage(),
        new RNThreadPackage(mReactNativeHost)  // <-- Here
      );
    }
```

Also note that only the official react native modules are available from your
threads (vibration, fetch, etc...). To include additional native modules in your
threads, pass them into the `RNThreadPackage` constructor after the `mReactNativeHost`
like this:
`new RNThreadPackage(mReactNativeHost, new ExampleNativePackage(), new SQLitePackage())`

43 44 45 46 47 48 49 50 51 52 53 54 55 56
### Manual installation


#### iOS

1. In XCode, in the project navigator, right click `Libraries``Add Files to [your project's name]`
2. Go to `node_modules``react-native-thread` and add `RNThread.xcodeproj`
3. In XCode, in the project navigator, select your project. Add `libRNThread.a` to your project's `Build Phases``Link Binary With Libraries`
4. Run your project (`Cmd+R`)<

#### Android

1. Open up `android/app/src/main/java/[...]/MainActivity.java`
  - Add `import com.reactlibrary.RNThreadPackage;` to the imports at the top of the file
57 58 59 60 61 62 63
  - Add `new RNThreadPackage(mReactNativeHost)` to the list returned by the `getPackages()` method
  - Also note that only the official react native modules are available from your
    threads (vibration, fetch, etc...). To include additional native modules in your
    threads, pass them into the `RNThreadPackage` constructor after the `mReactNativeHost`
    like this:
    `new RNThreadPackage(mReactNativeHost, new ExampleNativePackage(), new SQLitePackage())`

64 65 66 67 68 69 70 71 72 73 74
2. Append the following lines to `android/settings.gradle`:
  	```
  	include ':react-native-thread'
  	project(':react-native-thread').projectDir = new File(rootProject.projectDir, 	'../node_modules/react-native-thread/android')
  	```
3. Insert the following lines inside the dependencies block in `android/app/build.gradle`:
  	```
      compile project(':react-native-thread')
  	```

#### Windows
75 76
Windows support is not yet implemented, but PRs are welcome if you want to give it a shot!

77 78 79 80 81 82 83 84 85
[Read it! :D](https://github.com/ReactWindows/react-native)

1. In Visual Studio add the `RNThread.sln` in `node_modules/react-native-thread/windows/RNThread.sln` folder to their solution, reference from their app.
2. Open up your `MainPage.cs` app
  - Add `using Thread.RNThread;` to the usings at the top of the file
  - Add `new RNThreadPackage()` to the `List<IReactPackage>` returned by the `Packages` method


## Usage
86 87 88

In your application code (react components, etc.):

89
```javascript
90 91 92 93 94 95 96
import { Thread } from 'react-native-threads';

// start a new react native JS process
const thread = new Thread('path/to/thread.js');

// send a message, strings only
thread.postMessage('hello');
97

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
// listen for messages
thread.onMessage = (message) => console.log(message);

// stop the JS process
thread.terminate();
```

In your thread code (dedicated file such as `thread.js`):
```javascript
import { self } from 'react-native-threads';

// listen for messages
self.onmessage = (message) => {
}

// send a message, strings only
self.postMessage('hello');
115
```
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132

Check out the examples directory in this repo for demos of using `react-native-thread`
in a functioning app!

### Thread Lifecycle

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

### Debugging

Instantiating Threads creates multiple react native JS processes and can make debugging
remotely behave unpredictably. I recommend using a third party debugging tool like
[Reactotron](https://github.com/infinitered/reactotron) to aid with this. Each process,
including your main application as well as your thread code can connect to Reactotron
and log debugging messages.
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

## Acknowledgements

This library was heavily inspired by two other packages both under the name of
`react-native-workers`.

The first was https://github.com/fabriciovergal/react-native-workers ,
and the second was https://github.com/devfd/react-native-workers

I ended up going with devfd's implementation strategy as it seemed more flexible
and feature-rich to me.  At the time of this writing neither library was functioning
on the latest version of react native, and neither seemed to be very actively maintained.

This library would not exist without those two reference implementations to guide me!