UNPKG

2.8 kBPlain TextView Raw
1'use strict';
2import { isWorkletFunction } from './commonTypes';
3import type { WorkletFunction } from './commonTypes';
4import { setupCallGuard, setupConsole } from './initializers';
5import NativeReanimatedModule from './NativeReanimated';
6import { shouldBeUseWeb } from './PlatformChecker';
7import {
8 makeShareableCloneOnUIRecursive,
9 makeShareableCloneRecursive,
10} from './shareables';
11
12const SHOULD_BE_USE_WEB = shouldBeUseWeb();
13
14export type WorkletRuntime = {
15 __hostObjectWorkletRuntime: never;
16 readonly name: string;
17};
18
19/**
20 * Lets you create a new JS runtime which can be used to run worklets possibly on different threads than JS or UI thread.
21 *
22 * @param name - A name used to identify the runtime which will appear in devices list in Chrome DevTools.
23 * @param initializer - An optional worklet that will be run synchronously on the same thread immediately after the runtime is created.
24 * @returns WorkletRuntime which is a jsi::HostObject\<reanimated::WorkletRuntime\> - {@link WorkletRuntime}
25 * @see https://docs.swmansion.com/react-native-reanimated/docs/threading/createWorkletRuntime
26 */
27// @ts-expect-error Check `runOnUI` overload.
28export function createWorkletRuntime(
29 name: string,
30 initializer?: () => void
31): WorkletRuntime;
32
33export function createWorkletRuntime(
34 name: string,
35 initializer?: WorkletFunction<[], void>
36): WorkletRuntime {
37 return NativeReanimatedModule.createWorkletRuntime(
38 name,
39 makeShareableCloneRecursive(() => {
40 'worklet';
41 setupCallGuard();
42 setupConsole();
43 initializer?.();
44 })
45 );
46}
47
48// @ts-expect-error Check `runOnUI` overload.
49export function runOnRuntime<Args extends unknown[], ReturnValue>(
50 workletRuntime: WorkletRuntime,
51 worklet: (...args: Args) => ReturnValue
52): WorkletFunction<Args, ReturnValue>;
53/**
54 * Schedule a worklet to execute on the background queue.
55 */
56export function runOnRuntime<Args extends unknown[], ReturnValue>(
57 workletRuntime: WorkletRuntime,
58 worklet: WorkletFunction<Args, ReturnValue>
59): (...args: Args) => void {
60 'worklet';
61 if (__DEV__ && !SHOULD_BE_USE_WEB && !isWorkletFunction(worklet)) {
62 throw new Error(
63 '[Reanimated] The function passed to `runOnRuntime` is not a worklet.' +
64 (_WORKLET
65 ? ' Please make sure that `processNestedWorklets` option in Reanimated Babel plugin is enabled.'
66 : '')
67 );
68 }
69 if (_WORKLET) {
70 return (...args) =>
71 global._scheduleOnRuntime(
72 workletRuntime,
73 makeShareableCloneOnUIRecursive(() => {
74 'worklet';
75 worklet(...args);
76 })
77 );
78 }
79 return (...args) =>
80 NativeReanimatedModule.scheduleOnRuntime(
81 workletRuntime,
82 makeShareableCloneRecursive(() => {
83 'worklet';
84 worklet(...args);
85 })
86 );
87}