|
1 | | -# react-native-workers |
| 1 | +# react-native-workers |
| 2 | + |
| 3 | +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 :fireworks: |
| 4 | + |
| 5 | +## Features |
| 6 | +- JS workers run on both iOS and Android |
| 7 | +- access all native modules from the workers (network, geolocation, async storage ...) |
| 8 | +- write your Android Services in JS :tada: |
| 9 | + |
| 10 | +## Warning |
| 11 | +This plugin is still in beta and some features are missing. Current restrictions include: |
| 12 | +- worker files are only loaded from http://localhost:8081. |
| 13 | +- worker files are not yet packaged with your application. |
| 14 | +- no HMR support. no hot-reload support. |
| 15 | + |
| 16 | +## Installation |
| 17 | + |
| 18 | +```bash |
| 19 | +npm install react-native-workers --save |
| 20 | +``` |
| 21 | + |
| 22 | +## Setup |
| 23 | + |
| 24 | +### iOS |
| 25 | + |
| 26 | +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`. |
| 27 | +2. Add `libWorkers.a` to `Build Phases -> Link Binary With Libraries. |
| 28 | + |
| 29 | +## API |
| 30 | + |
| 31 | +From your application: |
| 32 | +```js |
| 33 | +import { Worker } from 'react-native-workers'; |
| 34 | + |
| 35 | +/* start worker */ |
| 36 | +const worker = new Worker("path/to/js/worker"); |
| 37 | + |
| 38 | +/* post message to worker. String only ! */ |
| 39 | +worker.postMessage("hello from application"); |
| 40 | + |
| 41 | +/* get message from worker. String only ! */ |
| 42 | +worker.onmessage = (message) => { |
| 43 | + |
| 44 | +} |
| 45 | + |
| 46 | +/* stop worker */ |
| 47 | +worker.terminate(); |
| 48 | + |
| 49 | +``` |
| 50 | + |
| 51 | +From your worker: |
| 52 | +```js |
| 53 | +import { self } from 'react-native-workers'; |
| 54 | + |
| 55 | +/* get message from application. String only ! */ |
| 56 | +self.onmessage = (message) => { |
| 57 | +} |
| 58 | + |
| 59 | +/* post message to application. String only ! */ |
| 60 | +self.postMessage("hello from worker"); |
| 61 | +``` |
| 62 | + |
| 63 | +##### Reload your application to restart your worker with the latest bundle version |
0 commit comments