Commit 49604e04 authored by Travis Nuttall's avatar Travis Nuttall

add simple example to demonstrate basic thread usage and debugging

parent d0985ced
......@@ -12,14 +12,15 @@
; For RN Apps installed via npm, "Libraries" folder is inside
; "node_modules/react-native" but in the source repo it is in the root
.*/Libraries/react-native/React.js
.*/Libraries/react-native/ReactNative.js
; Ignore polyfills
.*/Libraries/polyfills/.*
[include]
[libs]
node_modules/react-native/Libraries/react-native/react-native-interface.js
node_modules/react-native/flow
flow/
node_modules/react-native/flow/
[options]
emoji=true
......@@ -32,14 +33,16 @@ module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|we
suppress_type=$FlowIssue
suppress_type=$FlowFixMe
suppress_type=$FlowFixMeProps
suppress_type=$FlowFixMeState
suppress_type=$FixMe
suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(4[0-9]\\|[1-3][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)
suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(4[0-9]\\|[1-3][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+
suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(5[0-3]\\|[1-4][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)
suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(5[0-3]\\|[1-4][0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+
suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy
suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError
unsafe.enable_getters_and_setters=true
[version]
^0.49.1
^0.53.0
......@@ -46,8 +46,8 @@ buck-out/
# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
# screenshots whenever they are needed.
# For more information about the recommended setup visit:
# https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md
# https://docs.fastlane.tools/best-practices/source-control/
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
*/fastlane/report.xml
*/fastlane/Preview.html
*/fastlane/screenshots
import React, { Component } from 'react';
import {
AppRegistry,
Button,
StyleSheet,
Text,
View,
TouchableOpacity,
View
} from 'react-native';
import { Thread } from 'react-native-threads';
class ThreadExample extends Component {
export default class App extends Component<{}> {
state = { messages: [] }
workerThread = null;
componentDidMount() {
this.worker= new Thread('worker.js');
this.workerThread = new Thread('./worker.thread.js');
this.workerThread.onmessage = this.handleMessage;
}
this.worker.onmessage = (message) => {
console.log("Got message from worker", message);
}
componentWillUnmount() {
this.workerThread.terminate();
this.workerThread = null;
}
render() {
handleMessage = message => {
console.tron.log(`APP: got message ${message}`);
this.setState(state => {
return { messages: [...state.messages, message] };
});
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={() => {
console.log('SENDING MESSAGE TO WORKER');
this.worker.postMessage("Hello from main thread");
}}>
<Text style={styles.welcome}>
Send message
</Text>
</TouchableOpacity>
<Text style={styles.welcome}>
Welcome to React Native Threads!
</Text>
<Button title="Send Message To Worker Thread" onPress={() => {
this.workerThread.postMessage('Hello')
}} />
<View>
<Text>Messages:</Text>
{this.state.messages.map((message, i) => <Text key={i}>{message}</Text>)}
</View>
</View>
);
}
......@@ -46,13 +61,5 @@ const styles = StyleSheet.create({
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
}
});
AppRegistry.registerComponent('ThreadExample', () => ThreadExample);
# React Native Threads Simple Example
A simple example of using react-native-threads.
A single button sends a message to the worker thread, and the thread responds
with a message count that is displayed in the UI.
This example also shows how to use Reactotron for debugging.
## Running the example
I assume that you have Node.js, react-native-cli, and the necessary iOS/Android
dependencies installed.
To see debugging messages, [install Reactotron](https://github.com/infinitered/reactotron/blob/master/docs/installing.md)
and open it before running the app.
```shell
git clone https://github.com/Traviskn/react-native-threads.git
cd react-native-threads/examples/SimpleExample
npm install
react-native run-ios
# or
react-native run-android
```
To run in release mode first build the release thread bundles with the example's
npm scripts:
```shell
npm run build-thread-ios
npm run build-thread-android
```
import 'react-native';
import React from 'react';
import Index from '../index.ios.js';
import App from '../App';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
<App />
);
});
......@@ -45,12 +45,12 @@ android_library(
android_build_config(
name = "build_config",
package = "com.threadexample",
package = "com.simpleexample",
)
android_resource(
name = "res",
package = "com.threadexample",
package = "com.simpleexample",
res = "src/main/res",
)
......
......@@ -72,6 +72,10 @@ import com.android.build.OutputFile
* ]
*/
project.ext.react = [
entryFile: "index.js"
]
apply from: "../../node_modules/react-native/react.gradle"
/**
......@@ -94,7 +98,7 @@ android {
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "com.threadexample"
applicationId "com.simpleexample"
minSdkVersion 16
targetSdkVersion 22
versionCode 1
......@@ -133,7 +137,7 @@ android {
}
dependencies {
compile project(':react-native-thread')
compile project(':react-native-threads')
compile fileTree(dir: "libs", include: ["*.jar"])
compile "com.android.support:appcompat-v7:23.0.1"
compile "com.facebook.react:react-native:+" // From node_modules
......
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.threadexample"
package="com.simpleexample"
android:versionCode="1"
android:versionName="1.0">
......
package com.threadexample;
package com.simpleexample;
import com.facebook.react.ReactActivity;
......@@ -10,6 +10,6 @@ public class MainActivity extends ReactActivity {
*/
@Override
protected String getMainComponentName() {
return "ThreadExample";
return "SimpleExample";
}
}
package com.threadexample;
package com.simpleexample;
import android.app.Application;
......@@ -23,10 +23,15 @@ public class MainApplication extends Application implements ReactApplication {
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNThreadPackage(mReactNativeHost)
new MainReactPackage(),
new RNThreadPackage()
);
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
......
<resources>
<string name="app_name">ThreadExample</string>
<string name="app_name">SimpleExample</string>
</resources>
rootProject.name = 'SimpleExample'
include ':react-native-threads'
project(':react-native-threads').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-threads/android')
include ':app'
{
"name": "SimpleExample",
"displayName": "SimpleExample"
}
\ No newline at end of file
import Reactotron from 'reactotron-react-native'
console.tron = { log: Function.prototype };
if (__DEV__) {
Reactotron
.configure()
.useReactNative()
.connect();
console.tron = Reactotron;
}
import { AppRegistry } from 'react-native';
import App from './App';
import './config';
AppRegistry.registerComponent('SimpleExample', () => App);
......@@ -29,9 +29,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E47A1E0B4A5D006451C7"
BuildableName = "ThreadExample-tvOS.app"
BlueprintName = "ThreadExample-tvOS"
ReferencedContainer = "container:ThreadExample.xcodeproj">
BuildableName = "SimpleExample-tvOS.app"
BlueprintName = "SimpleExample-tvOS"
ReferencedContainer = "container:SimpleExample.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
......@@ -43,9 +43,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E48F1E0B4A5D006451C7"
BuildableName = "ThreadExample-tvOSTests.xctest"
BlueprintName = "ThreadExample-tvOSTests"
ReferencedContainer = "container:ThreadExample.xcodeproj">
BuildableName = "SimpleExample-tvOSTests.xctest"
BlueprintName = "SimpleExample-tvOSTests"
ReferencedContainer = "container:SimpleExample.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
......@@ -61,9 +61,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E48F1E0B4A5D006451C7"
BuildableName = "ThreadExample-tvOSTests.xctest"
BlueprintName = "ThreadExample-tvOSTests"
ReferencedContainer = "container:ThreadExample.xcodeproj">
BuildableName = "SimpleExample-tvOSTests.xctest"
BlueprintName = "SimpleExample-tvOSTests"
ReferencedContainer = "container:SimpleExample.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
......@@ -71,9 +71,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E47A1E0B4A5D006451C7"
BuildableName = "ThreadExample-tvOS.app"
BlueprintName = "ThreadExample-tvOS"
ReferencedContainer = "container:ThreadExample.xcodeproj">
BuildableName = "SimpleExample-tvOS.app"
BlueprintName = "SimpleExample-tvOS"
ReferencedContainer = "container:SimpleExample.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
......@@ -94,9 +94,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E47A1E0B4A5D006451C7"
BuildableName = "ThreadExample-tvOS.app"
BlueprintName = "ThreadExample-tvOS"
ReferencedContainer = "container:ThreadExample.xcodeproj">
BuildableName = "SimpleExample-tvOS.app"
BlueprintName = "SimpleExample-tvOS"
ReferencedContainer = "container:SimpleExample.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
......@@ -113,9 +113,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "2D02E47A1E0B4A5D006451C7"
BuildableName = "ThreadExample-tvOS.app"
BlueprintName = "ThreadExample-tvOS"
ReferencedContainer = "container:ThreadExample.xcodeproj">
BuildableName = "SimpleExample-tvOS.app"
BlueprintName = "SimpleExample-tvOS"
ReferencedContainer = "container:SimpleExample.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
......
......@@ -29,9 +29,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "ThreadExample.app"
BlueprintName = "ThreadExample"
ReferencedContainer = "container:ThreadExample.xcodeproj">
BuildableName = "SimpleExample.app"
BlueprintName = "SimpleExample"
ReferencedContainer = "container:SimpleExample.xcodeproj">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
......@@ -43,9 +43,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "00E356ED1AD99517003FC87E"
BuildableName = "ThreadExampleTests.xctest"
BlueprintName = "ThreadExampleTests"
ReferencedContainer = "container:ThreadExample.xcodeproj">
BuildableName = "SimpleExampleTests.xctest"
BlueprintName = "SimpleExampleTests"
ReferencedContainer = "container:SimpleExample.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
......@@ -54,6 +54,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
......@@ -61,9 +62,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "00E356ED1AD99517003FC87E"
BuildableName = "ThreadExampleTests.xctest"
BlueprintName = "ThreadExampleTests"
ReferencedContainer = "container:ThreadExample.xcodeproj">
BuildableName = "SimpleExampleTests.xctest"
BlueprintName = "SimpleExampleTests"
ReferencedContainer = "container:SimpleExample.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
......@@ -71,18 +72,19 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "ThreadExample.app"
BlueprintName = "ThreadExample"
ReferencedContainer = "container:ThreadExample.xcodeproj">
BuildableName = "SimpleExample.app"
BlueprintName = "SimpleExample"
ReferencedContainer = "container:SimpleExample.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
......@@ -94,9 +96,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "ThreadExample.app"
BlueprintName = "ThreadExample"
ReferencedContainer = "container:ThreadExample.xcodeproj">
BuildableName = "SimpleExample.app"
BlueprintName = "SimpleExample"
ReferencedContainer = "container:SimpleExample.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
......@@ -113,9 +115,9 @@
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "ThreadExample.app"
BlueprintName = "ThreadExample"
ReferencedContainer = "container:ThreadExample.xcodeproj">
BuildableName = "SimpleExample.app"
BlueprintName = "SimpleExample"
ReferencedContainer = "container:SimpleExample.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
......
......@@ -18,10 +18,10 @@
{
NSURL *jsCodeLocation;
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"ThreadExample"
moduleName:@"SimpleExample"
initialProperties:nil
launchOptions:launchOptions];
rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
......
......@@ -18,7 +18,7 @@
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="ThreadExample" textAlignment="center" lineBreakMode="middleTruncation" baselineAdjustment="alignBaselines" minimumFontSize="18" translatesAutoresizingMaskIntoConstraints="NO" id="kId-c2-rCX">
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="SimpleExample" textAlignment="center" lineBreakMode="middleTruncation" baselineAdjustment="alignBaselines" minimumFontSize="18" translatesAutoresizingMaskIntoConstraints="NO" id="kId-c2-rCX">
<rect key="frame" x="20" y="140" width="441" height="43"/>
<fontDescription key="fontDescription" type="boldSystem" pointSize="36"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
......
......@@ -5,7 +5,7 @@
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>ThreadExample</string>
<string>SimpleExample</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
......
......@@ -16,11 +16,11 @@
#define TIMEOUT_SECONDS 600
#define TEXT_TO_LOOK_FOR @"Welcome to React Native!"
@interface ThreadExampleTests : XCTestCase
@interface SimpleExampleTests : XCTestCase
@end
@implementation ThreadExampleTests
@implementation SimpleExampleTests
- (BOOL)findSubviewInView:(UIView *)view matching:(BOOL(^)(UIView *view))test
{
......
fKWwYO"+62,
\ No newline at end of file
This diff is collapsed.
JpBŒS
\ No newline at end of file
{
"name": "SimpleExample",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest",
"build-thread-ios": "node node_modules/react-native/local-cli/cli.js bundle --dev false --assets-dest ./ios --entry-file worker.thread.js --platform ios --bundle-output ./ios/worker.thread.jsbundle",
"build-thread-android": "node node_modules/react-native/local-cli/cli.js bundle --dev false --assets-dest ./android/app/src/main/res/ --entry-file worker.thread.js --platform android --bundle-output ./android/app/src/main/ assets/threads/worker.thread.bundle"
},
"dependencies": {
"react": "16.0.0-beta.5",
"react-native": "0.49.5",
"react-native-threads": "file:../../"
},
"devDependencies": {
"babel-jest": "21.2.0",
"babel-preset-react-native": "4.0.0",
"jest": "21.2.1",
"react-test-renderer": "16.0.0-beta.5",
"reactotron-react-native": "1.12.3"
},
"jest": {
"preset": "react-native"
}
}
import { self } from 'react-native-threads';
import './config';
let count = 0;
self.onmessage = message => {
console.tron.log(`THREAD: got message ${message}`);
count++;
self.postMessage(`Message #${count} from worker thread!`);
}
import 'react-native';
import React from 'react';
import Index from '../index.android.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
rootProject.name = 'ThreadExample'
include ':react-native-thread'
project(':react-native-thread').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-thread/android')
include ':app'
{
"name": "ThreadExample",
"displayName": "ThreadExample"
}
\ No newline at end of file
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
} from 'react-native';
import { Thread } from 'react-native-threads';
class ThreadExample extends Component {
componentDidMount() {
this.worker= new Thread('worker.js');
this.worker.onmessage = (message) => {
console.log("Got message from worker", message);
}
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={() => {
console.log('SENDING MESSAGE TO WORKER');
this.worker.postMessage("Hello from main thread");
}}>
<Text style={styles.welcome}>
Send message
</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('ThreadExample', () => ThreadExample);
{
"name": "ThreadExample",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "16.0.0-alpha.12",
"react-native": "0.48.3",
"react-native-threads": "file:../../"
},
"devDependencies": {
"babel-jest": "21.0.2",
"babel-preset-react-native": "4.0.0",
"jest": "21.1.0",
"react-test-renderer": "16.0.0-alpha.12"
},
"jest": {
"preset": "react-native"
}
}
import { self } from 'react-native-threads';
/*
* Web Worker
* you have access to all RN native modules (timeout, fetch, AsyncStorage, Vibration ...)
*/
// receive messages from main thread
self.onmessage = (message) => {
console.log('worker received message', message);
}
function ping() {
// send messages to main thread
console.log('SENDING PING FROM WORKER TO MAIN');
self.postMessage("Ping");
setTimeout(ping, 5000);
}
setTimeout(ping, 5000);
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment