| Files | Last commit | Last update |
|---|---|---|
| 1 month ago | ||
| 2 months ago | ||
| 1 month ago | ||
| 2 months ago | ||
| 5 days ago | ||
| 5 days ago | ||
| 1 month ago | ||
| 9 months ago |
Template version: v0.4.2
react-native-worklets
English | 简体中文
This project is developed based on react-native-worklets.
The repository of this third-party library has been migrated to Gitcode and can be downloaded directly from npm. The new package name is: @react-native-ohos/react-native-worklets. The version correspondence is as follows:
| Name | Version (npm Address) | Release Information | Supported RN Version | Supported Autolink | Compile API Version | Community Baseline Version | Source Address |
|---|---|---|---|---|---|---|---|
| @react-native-ohos/react-native-worklets | ~ 1.2.0(in progress) | Gitcode Releases | 0.86.* | Yes | API12+ | 0.12.2 | master |
| @react-native-ohos/react-native-worklets | ~ 1.1.0(in progress) | Gitcode Releases | 0.84.* | Yes | API12+ | 0.11.4 | br_rnoh0.84 |
| @react-native-ohos/react-native-worklets | ~ 1.0.1 | Gitcode Releases | 0.82.* | No | API12+ | 0.7.1 | br_rnoh0.82 |
Introduction
react-native-worklets is a multithreading library for React Native. Since react-native-reanimated >= 4.0.0 it has been split out of reanimated as its underlying dependency, and it can also be used standalone. Through the worklet mechanism (with the Babel plugin converting functions marked with 'worklet' into a serializable, cross-thread transferable form), it provides the ability to schedule code execution among the UI thread, the RN (JS) thread, and custom Worklet Runtimes, together with infrastructure for cross-runtime shared data (Serializable / Synchronizable / Shareable) and runtime-kind checks.
You can use the worklets capability standalone, or together with `@react-native-ohos/react-native-reanimated` (>= 4.0.0, whose native side depends on this library).
Installation and Usage
Go to the project directory and execute the following command:
npm
npm install react-native-worklets@0.12.2
npm install @react-native-ohos/react-native-worklets
yarn
yarn add react-native-worklets@0.12.2
yarn add @react-native-ohos/react-native-worklets
Plugin Configuration
Add the react-native-worklets/plugin plugin to babel.config.js:
Why is this needed? The Babel plugin automatically converts special JavaScript functions (called worklets) so that they can be passed around and run on the UI thread.
module.exports = {
presets: [
... // don't add it here :)
],
plugins: [
...
'react-native-worklets/plugin',
],
};
Clear the Metro cache (recommended):
npm
npm start --reset-cache
yarn
yarn start --reset-cache
Link
| Is supported autolink | Supported RN Version | |
|---|---|---|
| ~ 1.2.0 | Yes | 0.86 |
Projects using AutoLink need to be configured according to this document, Autolink Framework Guide Documentation: https://gitcode.com/CPF-RN/ohos_react_native/blob/master/docs/zh-cn/Autolinking.md
If the version you use supports Autolink and the project has been connected to Autolink, skip the ManualLink configuration.
ManualLink: this step is a guide to manually configure native dependencies.
First, use DevEco Studio to open the HarmonyOS project harmony in the project directory.
1. Overrides RN SDK
To make the project depend on the same version of the RN SDK, add the overrides field to the oh-package.json5 in the project root directory, pointing to the RN SDK version that the project needs to use. The overridden version can be a specific version number, an ambiguous version, or a local HAR file or source code directory.
For the role of this field, please read the official documentation
{
...
"overrides": {
"@rnoh/react-native-openharmony" : "~0.86.1",
}
}
2. Introducing Native Code
There are currently two methods:
- Use the HAR file;
- Directly link to the source code.
Method 1: Use the HAR file (recommended)
The HAR file is stored in the `harmony` directory in the installation path of the third-party library.
Open entry/oh-package.json5 and add the following dependencies:
"dependencies": {
"@rnoh/react-native-openharmony": "~0.86.1",
"@react-native-ohos/react-native-worklets": "file:../../node_modules/@react-native-ohos/react-native-worklets/harmony/worklets.har"
}
Click the sync button in the upper right corner.
Alternatively, run the following command on the terminal:
cd entry
ohpm install
Method 2: Directly link to the source code.
To directly link to the source code, please refer to [Directly Linking Source Code](https://gitcode.com/CPF-RN/usage-docs/blob/master/zh-cn/link-source-code.md)
3. Configure CMakeLists and Introducing ReanimatedWorkletPackage
Open entry/src/main/cpp/CMakeLists.txt and add:
project(rnapp)
cmake_minimum_required(VERSION 3.4.1)
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
+ set(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../react-native-harmony/harmony/cpp")
# (Optional) If you need to enable flags, please refer to the following configuration as needed:
+ add_compile_definitions(WORKLETS_FEATURE_FLAGS="[RUNTIME_TEST_FLAG:false][FETCH_PREVIEW_ENABLED:false][IOS_DYNAMIC_FRAMERATE_ENABLED:true][ENABLE_CROSS_RUNTIME_STACK_TRACES:true]")
add_subdirectory("${RNOH_CPP_DIR}" ./rn)
# RNOH_END: manual_package_linking_1
add_subdirectory("../../../../sample_package/src/main/cpp" ./sample-package)
+ add_subdirectory("${OH_MODULES}/@react-native-ohos/react-native-worklets/src/main/cpp" ./worklets)
# RNOH_END: manual_package_linking_1
add_library(rnoh_app SHARED
"./PackageProvider.cpp"
"${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp"
)
target_link_libraries(rnoh_app PUBLIC rnoh)
# RNOH_BEGIN: manual_package_linking_2
target_link_libraries(rnoh_app PUBLIC rnoh_sample_package)
+ target_link_libraries(rnoh_app PUBLIC rnoh_worklets)
# RNOH_BEGIN: manual_package_linking_2
Open entry/src/main/cpp/PackageProvider.cpp and add:
#include "RNOH/PackageProvider.h"
#include "SamplePackage.h"
+ #include "ReanimatedWorkletPackage.h"
using namespace rnoh;
std::vector<std::shared_ptr<Package>> PackageProvider::getPackages(Package::Context ctx) {
return {
std::make_shared<SamplePackage>(ctx),
+ std::make_shared<ReanimatedWorkletPackage>(ctx)
};
}
4. Introducing ReanimatedWorkletPackage to ArkTS
Open entry/src/main/ets/RNPackagesFactory.ets and add:
...
+ import { ReanimatedWorkletPackage } from '@react-native-ohos/react-native-worklets'
export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
return [
new SamplePackage(ctx),
+ new ReanimatedWorkletPackage(ctx),
];
}
Running
Click the sync button in the upper right corner.
Alternatively, run the following command on the terminal:
cd entry
ohpm install
Then build and run the project.
Constraints
Compatibility
This document is verified based on the following versions:
- RNOH: 0.86.1; SDK: HarmonyOS 6.0.1 Release SDK; IDE: DevEco Studio 6.0.1.260; ROM: 6.0.0.130 SP15;
Usage Example
The following code demonstrates the basic usage scenario of this library:
When using, the name of the imported library remains unchanged.
import { runOnUIAsync } from 'react-native-worklets';
import React, { useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default function RunOnUIAsyncExample() {
const [textResult, setTextResult] = useState<string>('');
const result: Promise<string> = runOnUIAsync((): string => {
return 'runOnUIAsync';
});
return (
<View style={styles.container}>
<Text>runOnUIAsync: {textResult}</Text>
<Button
title="run"
onPress={async () => {
const str = await result;
setTextResult(JSON.stringify(str));
}}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: 'white',
},
});
API
The **Platform** column indicates the platform where the properties are supported in the original third-party library.
If the value of **OpenHarmony Platform Support** is **yes**, it means that the OpenHarmony platform supports this property; **no** means the opposite; **partially** means some capabilities of this property are supported. The usage method is the same on different platforms and the effect is the same as that of iOS or Android.
Properties
WorkletRuntimeConfig (createWorkletRuntime config)
| Name | Type | Default | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|
name |
string | none | No | All | Yes | Name of the Worklet Runtime, used for debugging and stack traces |
initializer |
() => void | none | No | All | Yes | Initialization worklet that runs immediately after the runtime is created and before any other worklets |
animationQueuePollingRate |
number | 16 | No | All | Yes | Polling interval (in ms) between polls of requestAnimationFrame callbacks |
enableEventLoop |
boolean | true | No | All | Yes | Whether to enable the default Event Loop (provides setTimeout / setInterval / requestAnimationFrame, etc.); cannot be enabled when enableLocking is false |
enableLocking |
boolean | true | No | All | Yes | Whether to enable the cross-thread mutex for the runtime (synchronized access to Synchronizables relies on it); defaults to true and can only be disabled together with the Event Loop |
queue |
'default' | object | null | 'default' | No | All | Yes | Scheduling queue: 'default' for the built-in queue, an object for a custom AsyncQueue, null for no queue |
WorkletRuntime (createWorkletRuntime return value)
| Name | Type | Default | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|
name |
string | none | No | All | Yes | Runtime name (read-only) |
runtimeId |
number | none | No | All | Yes | Runtime identifier (read-only), used by id-based scheduling APIs such as scheduleOnRuntimeWithId |
Synchronizable (createSynchronizable return value)
A shared value with synchronous cross-runtime access, which can be read and written directly in worklets:
| Name | Type | Default | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|
getDirty |
() => Value | none | No | All | Yes | Non-blocking read of the current value (may read an unlocked "dirty" value) |
getBlocking |
() => Value | none | No | All | Yes | Blocking read of the current value (locked) |
setBlocking |
(value: Value | ((prev: Value) => Value)) => void | none | No | All | Yes | Blocking write, accepts a direct value or an updater function |
lock |
() => void | none | No | All | Yes | Acquire the lock (mutual exclusion across runtimes) |
unlock |
() => void | none | No | All | Yes | Release the lock |
Shareable (shared object created by createShareable)
A shared object tied to a host Worklet Runtime: on the host side it is a ShareableHost (holding the value directly), and on every other runtime it is a ShareableGuest (a proxy for reads and writes):
| Name | Side | Type | Default | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|---|
value |
Host | Value | none | No | All | Yes | Shared value held on the host side (direct read/write) |
getAsync |
Guest | () => Promise<Value> | none | No | All | Yes | Asynchronously read the shared value |
getSync |
Guest | () => Value | none | No | All | Yes | Synchronously read the shared value |
setAsync |
Guest | (value: Value | ((prev: Value) => Value)) => void | none | No | All | Yes | Asynchronously write the shared value, accepts an updater function |
setSync |
Guest | (value: Value | ((prev: Value) => Value)) => void | none | No | All | Yes | Synchronously write the shared value, accepts an updater function |
hostDecorator |
config parameter | (shareable: ShareableHost) => ShareableHost | none | No | All | Yes | Worklet decorating the host object (must return the same reference) |
guestDecorator |
config parameter | (shareable: ShareableGuest) => ShareableGuest | none | No | All | Yes | Worklet decorating each guest object (must return the same reference) |
initSynchronously |
config parameter | boolean | false | No | All | Yes | Whether to create the host synchronously during the createShareable call (lazily by default) |
RegistrationData (registerCustomSerializable parameter)
| Name | Type | Default | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|
name |
string | none | Yes | All | Yes | Unique name of the Custom Serializable (duplicate registration warns) |
determine |
(value: object) => boolean | none | Yes | All | Yes | Worklet that checks whether a given value belongs to this custom type |
pack |
(value: TValue) => TPacked | none | Yes | All | Yes | Worklet that packs the value into a serializable-by-default form before serialization |
unpack |
(value: TPacked) => TValue | none | Yes | All | Yes | Worklet that restores the packed value back into the original JavaScript value after deserialization |
APIs
Thread Scheduling (UI thread / RN thread)
| Name | Type | Parameter Type | Return Value | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|---|
runOnUI |
function | (worklet: (...args) => ReturnValue) | (...args) => void | No | All | Yes | Returns a wrapper that asynchronously schedules the worklet onto the UI thread when called |
runOnUIAsync |
function | (worklet: (...args) => ReturnValue, ...args) | Promise<ReturnValue> | No | All | Yes | Asynchronously runs the worklet on the UI thread, the Promise carries the return value |
runOnUISync |
function | (worklet: (...args) => ReturnValue, ...args) | ReturnValue | No | All | Yes | Synchronously runs the worklet on the UI Runtime and returns the result |
executeOnUIRuntimeSync |
function | (worklet: (...args) => ReturnValue) | (...args) => ReturnValue | No | All | Yes | Returns a wrapper that executes synchronously on the UI Runtime when called |
scheduleOnUI |
function | (worklet: (...args) => ReturnValue, ...args) | void | No | All | Yes | Immediately schedules the worklet onto the UI thread (no return value) |
runOnJS |
function | (fun: (...args) => ReturnValue) | (...args) => void | No | All | Yes | Returns a wrapper that asynchronously schedules the function back onto the RN thread when called |
scheduleOnRN |
function | (fun: (...args) => ReturnValue, ...args) | void | No | All | Yes | Immediately schedules the function onto the RN thread microtask queue |
Worklet Runtime
| Name | Type | Parameter Type | Return Value | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|---|
createWorkletRuntime |
function | (config?: WorkletRuntimeConfig) or (name?, initializer?) | WorkletRuntime | No | All | Yes | Creates a custom JS runtime (which can run on a thread other than the JS / UI threads) |
runOnRuntime |
function | (workletRuntime: WorkletRuntime, worklet) | WorkletFunction (async execution wrapper) | No | All | Yes | Returns a wrapper that asynchronously schedules the worklet onto the given runtime when called |
runOnRuntimeAsync |
function | (workletRuntime: WorkletRuntime, worklet, ...args) | Promise<ReturnValue> | No | All | Yes | Asynchronously runs the worklet on the given runtime, the Promise carries the return value |
runOnRuntimeAsyncWithId |
function | (runtimeId: number, worklet, ...args) | Promise<ReturnValue> | No | All | Yes | Same as runOnRuntimeAsync, targets the runtime by runtimeId |
runOnRuntimeSync |
function | (workletRuntime: WorkletRuntime, worklet, ...args) | ReturnValue | No | All | Yes | Synchronously runs the worklet on the given runtime and returns the result |
runOnRuntimeSyncWithId |
function | (runtimeId: number, worklet, ...args) | ReturnValue | No | All | Yes | Same as runOnRuntimeSync, targets the runtime by runtimeId |
scheduleOnRuntime |
function | (workletRuntime: WorkletRuntime, worklet, ...args) | void | No | All | Yes | Schedules the worklet onto the given runtime |
scheduleOnRuntimeWithId |
function | (runtimeId: number, worklet, ...args) | void | No | All | Yes | Same as scheduleOnRuntime, targets the runtime by runtimeId |
UIRuntimeId |
const | - | number (= RuntimeKind.UI = 2) | No | All | Yes | The runtimeId constant of the UI Runtime, used to specify the host in createShareable |
getUIRuntimeHolder |
function | () | object (UI Runtime Holder) | No | All | Yes | Returns the underlying Holder of the UI Runtime (internal / advanced usage) |
getUISchedulerHolder |
function | () | object (UI Scheduler Holder) | No | All | Yes | Returns the underlying Holder of the UI Runtime scheduler (internal / advanced usage) |
Runtime Kind Checks
| Name | Type | Parameter Type | Return Value | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|---|
getRuntimeKind |
function | () | RuntimeKind | No | All | Yes | Returns the kind of the current runtime (usable in worklets) |
isRNRuntime |
function | () | boolean | No | All | Yes | Whether the current runtime is the React Native Runtime |
isUIRuntime |
function | () | boolean | No | All | Yes | Whether the current runtime is the UI Runtime |
isWorkletRuntime |
function | () | boolean | No | All | Yes | Whether the current runtime is a Worklet Runtime (UI or Worker) |
isWorkerRuntime |
function | () | boolean | No | All | Yes | Whether the current runtime is a user-created Worker Runtime |
Sharing and Serialization
| Name | Type | Parameter Type | Return Value | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|---|
createShareable |
function | (hostRuntimeId: number, initial: Value, config?) | Shareable | No | All | Yes | Creates a cross-runtime shared object tied to a host Worklet Runtime |
isShareable |
function | (value: unknown) | boolean | No | All | Yes | Checks whether a given value is a Shareable (usable in worklets) |
createSerializable |
function | (value: Value) | SerializableRef | No | All | Yes | Recursively converts JavaScript values into Serializable references that can be passed across JavaScript Runtimes |
isSerializableRef |
function | (value: unknown) | boolean | No | All | Yes | Checks whether a given value is a Serializable reference |
registerCustomSerializable |
function | (registrationData: RegistrationData) | void | No | All | Yes | Registers custom packing / unpacking (serialization) logic for custom types |
serializableMappingCache |
const | - | { set, get } | No | All | Yes | Mapping cache between Serializable objects and references (internal usage) |
createSynchronizable |
function | (value: Value) | Synchronizable | No | All | Yes | Creates a Synchronizable with synchronous cross-thread read/write access |
isSynchronizable |
function | (value: unknown) | boolean | No | All | Yes | Checks whether a given value is a Synchronizable (usable in worklets) |
Deprecated
The following exports are kept for compatibility; prefer the corresponding replacements:
| Name | Type | Parameter Type | Return Value | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|---|
makeShareabledeprecated |
function | (value: Value) | Value (Serializable reference) | No | All | Yes | Deprecated, use createSerializable instead |
makeShareableCloneRecursivedeprecated |
function | (value, shouldPersistRemote?, depth?) | SerializableRef | No | All | Yes | Deprecated, use createSerializable instead |
makeShareableCloneOnUIRecursivedeprecated |
function | (value: Value) | SerializableRef | No | All | Yes | Deprecated, internal usage |
isShareableRefdeprecated |
function | (value: unknown) | boolean | No | All | Yes | Deprecated, use isSerializableRef instead |
shareableMappingCachedeprecated |
const | - | { set, get } | No | All | Yes | Deprecated, use serializableMappingCache instead |
callMicrotasksdeprecated |
function | () | void (NOOP) | No | All | Yes | Deprecated, a no-op kept only for backwards compatibility |
Worklet Utilities
| Name | Type | Parameter Type | Return Value | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|---|
isWorkletFunction |
function | (value: unknown) | boolean | No | All | Yes | Checks whether a function is a worklet (requires the Babel plugin; always returns false before the declaration is reached; meaningful only in the RN runtime) |
Feature Flags
| Name | Type | Parameter Type | Return Value | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|---|
getStaticFeatureFlag |
function | (name: keyof StaticFeatureFlagsSchema) | boolean | No | All | Yes | Reads a static feature flag (determined at compile time) |
setDynamicFeatureFlag |
function | (name: string, value: boolean) | void | No | All | Yes | Dynamically sets a feature flag |
getDynamicFeatureFlag |
function | (name: string) | boolean | No | All | Yes | Reads a dynamic feature flag |
Current static flags:
| Name | Type | Default | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|
RUNTIME_TEST_FLAG |
boolean | false | No | All | Yes | Runtime test flag (upstream testing purpose, no business consumption point in the source code); behavior on HarmonyOS is consistent with upstream |
FETCH_PREVIEW_ENABLED |
boolean | false | No | All | Yes | Whether to initialize the networking module on Worklet Runtimes in Bundle Mode (provides the fetch preview capability) |
IOS_DYNAMIC_FRAMERATE_ENABLED |
boolean | true | No | iOS | Yes | dynamic framerate (ProMotion adaptive refresh rate) flag |
ENABLE_CROSS_RUNTIME_STACK_TRACES |
boolean | true | No | All | Yes | Captures cross-runtime scheduling stacks in dev mode (__DEV__), helping locate error stacks across runtimes |
Debugging
| Name | Type | Parameter Type | Return Value | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|---|
isBundleModeEnabled |
function | () | boolean | No | All | Yes | Whether Bundle Mode is enabled (injected at build time by the Worklets Babel plugin) |
toggleSlowAnimationsOnUIRuntime |
function | () | boolean | No | All | Yes | Toggles the slow-animations debug mode on the UI Runtime (internal debugging usage) |
Native Module
| Name | Type | Parameter Type | Return Value | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|---|
WorkletsModule |
const | - | IWorkletsModule | No | All | Yes | Reference to the native WorkletsModule (TurboModule), internal / advanced usage |
Enums and Constants
| Name | Type | Value | Required | Platform | OpenHarmony Platform Support | Description |
|---|---|---|---|---|---|---|
RuntimeKind |
enum | ReactNative = 1, UI = 2, Worker = 3 | No | All | Yes | Runtime kind (returned by getRuntimeKind) |
UIRuntimeId |
const | 2 (= RuntimeKind.UI) | No | All | Yes | The runtimeId constant of the UI Runtime |
Known Issues
None.
Others
None.
Directory Structure
/rntpc_react-native-reanimated # Project root directory
├── package
│ ├── react-native-worklets # worklets HarmonyOS adaptation package (underlying dependency of reanimated >= 4.0.0)
│ │ ├── harmony # HarmonyOS adaptation code
│ │ │ └─ worklets.har # har package
│ │ │ └─ worklets # HarmonyOS adaptation core code
│ │ │ └─ src/main/cpp # C++ adaptation code (ReanimatedWorkletPackage)
│ │ │ └─ src/main/ets # ArkTS adaptation code
│ │ ├── src
│ │ │ └─ index.ts # Adaptation layer entry (re-exports the upstream JS exports)
│ │ └── package.json
│ └── react-native-reanimated # reanimated HarmonyOS adaptation package
├── example # Example project
└── README.OpenSource # Open source information
Contributing
If you encounter any problems during use, you can submit an Issue, and of course, PR are also very welcome.
License
This project is based on The MIT License (MIT) , please feel free to enjoy and contribute to open source.