diff --git a/packages/react-native-fantom/src/index.js b/packages/react-native-fantom/src/index.js index 0c3b79f7dbcd3b..179e0d7755fcb5 100644 --- a/packages/react-native-fantom/src/index.js +++ b/packages/react-native-fantom/src/index.js @@ -60,6 +60,17 @@ class Root { // TODO: add an API to check if all surfaces were deallocated when tests are finished. } +const DEFAULT_TASK_PRIORITY = schedulerPriorityImmediate; + +/** + * Schedules a task to run on the event loop. + * If the work loop is running, it will be executed according to its priority. + * Otherwise, it will wait in the queue until the work loop runs. + */ +export function scheduleTask(task: () => void | Promise) { + nativeRuntimeScheduler.unstable_scheduleCallback(DEFAULT_TASK_PRIORITY, task); +} + let flushingQueue = false; /* @@ -70,14 +81,23 @@ let flushingQueue = false; export function runTask(task: () => void | Promise) { if (flushingQueue) { throw new Error( - 'Nested runTask calls are not allowed. If you want to schedule a task from inside another task, use scheduleTask instead.', + 'Nested `runTask` calls are not allowed. If you want to schedule a task from inside another task, use `scheduleTask` instead.', ); } - nativeRuntimeScheduler.unstable_scheduleCallback( - schedulerPriorityImmediate, - task, - ); + scheduleTask(task); + runWorkLoop(); +} + +/** + * Runs the event loop until all tasks are executed. + */ +export function runWorkLoop(): void { + if (flushingQueue) { + throw new Error( + 'Cannot start the work loop because it is already running. If you want to schedule a task from inside another task, use `scheduleTask` instead.', + ); + } try { flushingQueue = true;