{"id":19056359,"url":"https://github.com/lamnhan066/isolate_manager","last_synced_at":"2025-08-22T06:32:51.477Z","repository":{"id":38268056,"uuid":"506285400","full_name":"lamnhan066/isolate_manager","owner":"lamnhan066","description":"Create multiple long-lived isolates for the Functions, supports Worker on the Web (with the effective generator) and WASM compilation.","archived":false,"fork":false,"pushed_at":"2024-10-30T03:03:35.000Z","size":3110,"stargazers_count":37,"open_issues_count":6,"forks_count":3,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-10-30T06:13:08.721Z","etag":null,"topics":["dart","flutter","isolate","plugin"],"latest_commit_sha":null,"homepage":"https://pub.dev/packages/isolate_manager","language":"Dart","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lamnhan066.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-06-22T14:37:17.000Z","updated_at":"2024-10-29T02:11:22.000Z","dependencies_parsed_at":"2023-02-16T04:46:09.315Z","dependency_job_id":"8759bcf9-f040-452d-b072-0fa5484d38d0","html_url":"https://github.com/lamnhan066/isolate_manager","commit_stats":null,"previous_names":["lamnhan066/isolate_manager"],"tags_count":93,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lamnhan066%2Fisolate_manager","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lamnhan066%2Fisolate_manager/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lamnhan066%2Fisolate_manager/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lamnhan066%2Fisolate_manager/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lamnhan066","download_url":"https://codeload.github.com/lamnhan066/isolate_manager/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":230568590,"owners_count":18246378,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dart","flutter","isolate","plugin"],"created_at":"2024-11-08T23:49:09.877Z","updated_at":"2025-08-22T06:32:51.460Z","avatar_url":"https://github.com/lamnhan066.png","language":"Dart","funding_links":["https://www.buymeacoffee.com/lamnhan066"],"categories":["Dart"],"sub_categories":[],"readme":"# Isolate Manager\n\n[![codecov](https://codecov.io/gh/lamnhan066/isolate_manager/graph/badge.svg?token=MSREWDRA4E)](https://codecov.io/gh/lamnhan066/isolate_manager)\n[![Pub Version](https://img.shields.io/pub/v/isolate_manager)](https://pub.dev/packages/isolate_manager)\n[![Pub Points](https://img.shields.io/pub/points/isolate_manager)](https://pub.dev/packages/isolate_manager)\n[![Pub Downloads](https://img.shields.io/pub/dm/isolate_manager)](https://pub.dev/packages/isolate_manager)\n[![Pub Likes](https://img.shields.io/pub/likes/isolate_manager)](https://pub.dev/packages/isolate_manager)\n\n[![PubStats Popularity](https://pubstats.dev/badges/packages/isolate_manager/popularity.svg)](https://pubstats.dev/packages/isolate_manager)\n[![PubStats Rank](https://pubstats.dev/badges/packages/isolate_manager/rank.svg)](https://pubstats.dev/packages/isolate_manager)\n[![PubStats Dependents](https://pubstats.dev/badges/packages/isolate_manager/dependents.svg)](https://pubstats.dev/packages/isolate_manager)\n\n**Isolate Manager** is a powerful Flutter/Dart package designed to simplify concurrent programming using isolates. It offers robust cross-platform support, including native, web (via JavaScript Workers), and WebAssembly (WASM).\n\n## Why Isolate Manager?\n\n* **Effortless Concurrency:** Takes the complexity out of Dart's isolates for smooth background processing.\n* **Truly Cross-Platform:** Write your concurrent code once and run it seamlessly on Dart VM, Web (auto-compiles to JS Workers), and WASM.\n* **Robust \u0026 Safe:** Provides built-in type and exception safety mechanisms, especially crucial for web worker communication.\n* **Optimized Performance:** Features smart task queuing, priority handling, and customizable strategies to fine-tune execution.\n* **Flexible Isolate Types:** Choose from one-off, multi-function, or single-function isolates to best suit your task's lifecycle.\n\n## Features\n\n* **Versatile Isolate Management:**\n  * **One-off Isolates:** Perfect for single, intensive computations. Supports web workers.\n  * **Multi-Function Isolates:** Reuse a single isolate for various functions, minimizing overhead.\n  * **Single-Function Isolates:** Dedicate an isolate to a specific, continuous task or data stream.\n* **Cross-Platform by Design:**\n  * **Web \u0026 WASM Ready:** Automatically compiles isolate functions into JavaScript Workers for web deployment.\n  * **Graceful Fallback:** Defaults to `Future`/`Stream` if Web Workers are unavailable.\n* **Intelligent Queue System:**\n  * Automatic task queuing.\n  * Support for priority tasks.\n  * Customizable queue overflow strategies.\n* **Type \u0026 Exception Safety:**\n  * Utilize specialized `ImType` wrappers (`ImNum`, `ImString`, etc.) for reliable data transfer with web workers.\n  * Propagate custom exceptions across isolate boundaries, even on the web.\n* **Developer-Friendly Extras:**\n  * **Custom Isolate Functions:** Gain full control over the isolate's lifecycle and communication.\n  * **Progress Reporting:** Send intermediate updates from long-running tasks.\n  * **Codeless Web Workers:** Generate necessary JavaScript worker files without `build_runner`.\n  * **Built-in Benchmark:** Compare performance of different concurrency models.\n\n## Getting Started\n\n### 1. Add Dependencies\n\nAdd the following to your `pubspec.yaml`:\n\n```yaml\ndependencies:\n  isolate_manager: ^latest_version # Use the latest version\n\ndev_dependencies:\n  isolate_manager_generator: ^latest_version # Required for web worker generation\n```\n\nThen, run `dart pub get` or `flutter pub get`.\n\n### 2. Important Prerequisite for Isolate Functions\n\nFunctions intended to run in an isolate **must** be:\n\n* A `static` method within a class, OR\n* A top-level function (defined outside any class).\n\nAdditionally, annotate these functions with `@pragma('vm:entry-point')` to prevent them from being removed by tree-shaking during compilation.\n\n\u003e **Note:** Worker annotations like `@isolateManagerWorker`, `@isolateManagerSharedWorker`, and `@isolateManagerCustomWorker` are provided by the `isolate_manager` package.\n\u003e Make sure to import them if you use them in your code.\n\n```dart\nimport 'package:isolate_manager/isolate_manager.dart';\n\n@pragma('vm:entry-point')\nint sum(List\u003cint\u003e numbers) {\n  return numbers.reduce((a, b) =\u003e a + b);\n}\n```\n\n### 3. Platform-Specific Setup\n\n#### Mobile \u0026 Desktop (VM)\n\nNo additional setup is required!\n\n#### Web (JavaScript Workers)\n\nTo use isolates on the web, your Dart functions need to be compiled into JavaScript Workers.\n\n* **Annotate Your Functions:**\n  Use specific annotations on the functions you want to be available as web workers. Run the generator after adding or modifying these.\n\n  * `@isolateManagerWorker`: For one-off or single-function isolates.\n  * `@isolateManagerSharedWorker`: For shared, multi-function isolates.\n  * `@isolateManagerCustomWorker`: For custom isolate functions where you manage communication manually.\n\n* **Data Transfer Limitations:**\n\n  * Functions for web workers must **not** depend on Flutter-specific libraries (e.g., `dart:ui`).\n  * Only Dart primitives (`num`, `String`, `bool`, `null`), and `Map` or `List` collections containing these primitives, are directly transferable.\n  * For other data types, use the provided [`ImType` wrappers](#ensuring-type-safety-web) or serialize/deserialize your data manually.\n\n* **Generate JS Workers:**\n  Run the following command in your terminal:\n\n  ```shell\n  dart run isolate_manager:generate\n  ```\n\n  (See [Web Worker Generator](#web-worker-generator) for more options.)\n\n#### WebAssembly (WASM) Notes\n\n* **Type Handling:** When using WASM, all `int` types (including those in collections) are treated as `double`. Isolate Manager provides a built-in converter to handle this automatically; you can disable it by setting `enableWasmConverter: false` if needed.\n* **Development Server Headers:** If your app hangs when running with `flutter run -d chrome --wasm`, you might need to set specific headers. Try:\n\n  ```shell\n  flutter run -d chrome --wasm --web-header=Cross-Origin-Opener-Policy=same-origin --web-header=Cross-Origin-Embedder-Policy=require-corp\n  ```\n\n## Usage Examples\n\n### One-off Isolate (Simple Task)\n\nIdeal for fire-and-forget computations.\n\n```dart\nimport 'package:isolate_manager/isolate_manager.dart';\n\n@pragma('vm:entry-point')\n@isolateManagerWorker // For web worker generation\nint fibonacciRecursive(int n) {\n  if (n \u003c 2) return n;\n  return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);\n}\n\nvoid main() async {\n  // Option 1: Explicit worker parameters (useful if function name differs or for clarity)\n  final result1 = await IsolateManager.run(\n    () =\u003e fibonacciRecursive(40),     // The actual function to execute\n    workerName: 'fibonacciRecursive', // Name used for JS worker mapping\n    workerParameter: 40,              // Parameter for the JS worker\n  );\n  print('Fibonacci(40) - Option 1: $result1');\n\n  // Option 2: Automatic worker mapping (concise)\n  final result2 = await IsolateManager.runFunction(fibonacciRecursive, 40);\n  print('Fibonacci(40) - Option 2: $result2');\n}\n```\n\n### Long-Lived Multi-Function Isolate\n\nReuse a single isolate for multiple different computations.\n\n```dart\nimport 'package:isolate_manager/isolate_manager.dart';\n\n@pragma('vm:entry-point')\n@isolateManagerSharedWorker\nFuture\u003cdouble\u003e addNumbersFuture(List\u003cdouble\u003e values) async {\n  return values[0] + values[1];\n}\n\n@pragma('vm:entry-point')\n@isolateManagerSharedWorker\nint multiplyNumbers(List\u003cint\u003e values) {\n  return values[0] * values[1];\n}\n\nvoid main() async {\n  final sharedIsolate = IsolateManager.createShared(\n    concurrent: 2,   // Number of tasks this isolate can handle concurrently\n    useWorker: true, // Enable web worker usage if on web\n    workerMappings: {\n      // Map Dart function references to their JS worker names\n      addNumbersFuture: 'addNumbersFuture',\n      multiplyNumbers: 'multiplyNumbers',\n    },\n  );\n\n  // Optional: Listen for intermediate values (if any function sends them)\n  sharedIsolate.stream.listen((value) {\n    print('Intermediate value from shared isolate: $value');\n  });\n\n  final sumResult = await sharedIsolate.compute(addNumbersFuture, [10.5, 20.3]);\n  print('Sum (shared): 10.5 + 20.3 = $sumResult');\n\n  final productResult = await sharedIsolate.compute(multiplyNumbers, [7, 6]);\n  print('Product (shared): 7 * 6 = $productResult');\n\n  await sharedIsolate.stop(); // Important to release resources\n  // Or use `sharedIsolate.restart()` to restart the isolate\n}\n```\n\n### Long-Lived Single-Function Isolate\n\nDedicate an isolate to a single, potentially continuous, function.\n\n```dart\nimport 'package:isolate_manager/isolate_manager.dart';\n\n@pragma('vm:entry-point')\n@isolateManagerWorker\nint complexCalculation(int initialValue) {\n  // Simulate a task that might send progress updates or run for a while\n  int result = initialValue;\n  for (int i = 0; i \u003c 5; i++) {\n    result += i * 2;\n    // If this were a custom function, you could send progress here\n  }\n  return result;\n}\n\nvoid main() async {\n  final singleFuncIsolate = IsolateManager.create(\n    complexCalculation, // The function this isolate is dedicated to\n    workerName: 'complexCalculation', // For JS worker\n    concurrent: 1, // Typically 1 for a single dedicated function\n  );\n\n  // Optional: Listen for intermediate values\n  singleFuncIsolate.stream.listen((value) {\n    print('Intermediate value from single-function isolate: $value');\n  });\n\n  final calculationResult = await singleFuncIsolate.compute(10); // `compute` is callable\n  print('Complex Calculation Result: $calculationResult');\n\n  await singleFuncIsolate.stop(); // Release resources\n  // Or use `singleFuncIsolate.restart()` to restart the isolate\n}\n```\n\n### Custom Function \u0026 Error Handling\n\nFor fine-grained control over the isolate's behavior, including sending multiple results or handling initialization/disposal.\n\n```dart\nimport 'dart:convert';\nimport 'package:isolate_manager/isolate_manager.dart';\n\n@pragma('vm:entry-point')\n@isolateManagerWorker // For web\nint fibonacci(int n) {\n  if (n \u003c 0) throw ArgumentError('Input cannot be negative.');\n  if (n \u003c 2) return n;\n  return fibonacci(n - 1) + fibonacci(n - 2);\n}\n\n@pragma('vm:entry-point')\n@isolateManagerCustomWorker\nvoid customFibonacciWorker(dynamic params) {\n  IsolateManagerFunction.customFunction\u003cint, int\u003e(\n    params,\n    onEvent: (controller, message) {\n      try {\n        final result = fibonacci(message);\n        controller.sendResult(result); // Send the final result\n      } catch (err, stack) {\n        // Send an IsolateException for structured error handling\n        controller.sendResultError(IsolateException(err.toString(), stack.toString()));\n      }\n      return 0; // Indicates completion for this event\n    },\n    onInit: (controller) {\n      print('Custom Fibonacci Worker: Initialized');\n      // Perform any setup logic here\n    },\n    onDispose: (controller) {\n      print('Custom Fibonacci Worker: Disposed');\n      // Perform any cleanup logic here\n    },\n    autoHandleException: false, // Set to true to let IsolateManager handle basic errors\n    autoHandleResult: false,    // Set to true to let IsolateManager handle basic result sending\n  );\n}\n\nvoid main() async {\n  final customIsolate = IsolateManager.createCustom(\n    customFibonacciWorker,\n    workerName: 'customFibonacciWorker', // For JS Worker\n    debugMode: true, // Enable more logging\n  );\n\n  try {\n    final result = await customIsolate.compute(10);\n    print('Custom Fibonacci(10): $result');\n\n    final resultNegative = await customIsolate.compute(-5); // This will throw\n    print('Custom Fibonacci(-5): $resultNegative');\n  } on IsolateException catch (e) {\n    print('Caught IsolateException: ${e.error}');\n    // print('Stack trace: ${e.stacktrace}');\n  } catch (e) {\n    print('Caught other error: $e');\n  } finally {\n    await customIsolate.stop();\n  }\n}\n```\n\n## Advanced Capabilities\n\n### Smart Queue Management\n\nControl how tasks are queued and processed when multiple requests are made to an isolate.\n\n* **Priority Tasks:** Add `priority: true` when calling `compute` or `run` to move a task to the front of its queue.\n\n* **Queue Size Limit:** Set `maxCount` in `IsolateManager.create`, `createShared`, or `createCustom` constructors to limit the number of pending tasks.\n\n* **Queue Strategies:** Define behavior when `maxCount` is reached:\n\n  * `UnlimitedStrategy()`: (Default) No limit on queued tasks.\n  * `DropNewestStrategy()`: Removes the most recently added task.\n  * `DropOldestStrategy()`: Removes the oldest task in the queue.\n  * `RejectIncomingStrategy()`: Rejects any new tasks if the queue is full.\n\n* **Custom Queue Strategy:** For custom logic, extend `QueueStrategy\u003cR, P\u003e`:\n\n  ```dart\n  class MyCustomStrategy\u003cR, P\u003e extends QueueStrategy\u003cR, P\u003e {\n    @override\n    bool continueIfMaxCountExceeded() {\n      // Access `queues`, `queuesCount`, `maxCount`\n      if (queuesCount \u003e= maxCount \u0026\u0026 queues.isNotEmpty) {\n        // Example: Allow if the oldest task is low priority (pseudo-code)\n        // if (queues.first.priority == false) {\n        //   print('Custom strategy: Dropping oldest to make space.');\n        //   queues.removeFirst(); // You'd need to manage this carefully\n        //   return true; // Allow the new task\n        // }\n        return false; // Reject by default if full\n      }\n      return true; // Allow if not full\n    }\n  }\n  ```\n\n  *Note: Modifying `queues` directly in `continueIfMaxCountExceeded` requires careful implementation to ensure consistency.*\n\n### Progress Updates\n\nReceive intermediate results from a task before it completes. This is typically used with `IsolateManager.createCustom`.\n\n\u003e In this example, progress updates are sent as JSON strings for demonstration purposes.\n\n```dart\n// In your main Dart code:\nvoid main() async {\n  final isolate = IsolateManager.createCustom(\n    longRunningTaskWithProgress,\n    workerName: 'longRunningTaskWithProgress', // For JS Worker\n  );\n\n  print('Starting task with progress updates...');\n  final result = await isolate.compute(\n    100, // Example parameter for the task\n    callback: (dynamic value) {\n      // `value` is what `controller.sendResult()` sends from the isolate\n      try {\n        final data = jsonDecode(value as String); // Assuming JSON string for progress\n        if (data.containsKey('progress')) {\n          print('Progress: ${data['progress']}%');\n          return false; // Indicates this is a progress update, not the final result\n        } else if (data.containsKey('finalResult')) {\n          print('Final result package received: ${data['finalResult']}');\n          return true; // Indicates this is the final result\n        }\n      } catch (e) {\n        print('Error decoding progress/result: $e');\n        return true; // Treat as error, stop listening\n      }\n      return true; // Default to stop if format is unexpected\n    },\n  );\n\n  print('Task completed with final processed value: $result');\n  await isolate.stop();\n}\n\n// In your isolate function (e.g., custom worker):\n@pragma('vm:entry-point')\n@isolateManagerCustomWorker\nvoid longRunningTaskWithProgress(dynamic params) {\n  IsolateManagerFunction.customFunction\u003cString, int\u003e(\n    params,\n    onEvent: (controller, totalSteps) {\n      for (int i = 0; i \u003c= totalSteps; i += 10) {\n        final progressReport = jsonEncode({'progress': i});\n        controller.sendResult(progressReport); // Send progress update\n      }\n      // Send the final result\n      return jsonEncode({'finalResult': totalSteps});\n    },\n  );\n}\n```\n\n### Ensuring Type Safety (Web)\n\nWhen working with Web Workers, data transfer is restricted. `IsolateManager` provides `ImType` wrappers for common types to ensure they are correctly (de)serialized.\n\n```dart\nimport 'package:isolate_manager/isolate_manager.dart';\n\n@pragma('vm:entry-point')\n@isolateManagerWorker\nImMap processDataWeb(ImList numbers) {\n  // 1. Unwrap to get standard Dart types (List\u003cdynamic\u003e in this case)\n  final nativeList = numbers.unwrap as List\u003cdynamic\u003e;\n\n  // 2. Process the data\n  final processedMap = \u003cImType, ImType\u003e{};\n  for (var i = 0; i \u003c nativeList.length; i++) {\n    final numVal = nativeList[i] as num; // Ensure type\n    processedMap[ImString('item_$i')] = ImNum(numVal * 2);\n  }\n\n  // 3. Wrap the result in an ImType\n  return ImMap(processedMap);\n}\n\nvoid main() async {\n  // On web, this will use the JS worker if generated.\n  final isolate = IsolateManager.create(\n    processDataWeb,\n    workerName: 'processDataWeb',\n  );\n\n  try {\n    // 1. Wrap your input data\n    final inputData = ImList.wrap([1, 2.5, 3]);\n\n    // 2. Compute\n    final ImMap result = await isolate.compute(inputData) as ImMap;\n\n    // 3. Unwrap the result\n    final nativeResult = result.unwrap as Map\u003cdynamic, dynamic\u003e;\n    nativeResult.forEach((key, value) {\n      print('Web Processed: ${key} -\u003e ${value}');\n    });\n\n  } on UnsupportedImTypeException catch (e) {\n    print('Error: Unsupported type used with ImType. ${e.message}');\n  } catch (e) {\n    print('An error occurred: $e');\n  } finally {\n    await isolate.stop();\n  }\n}\n```\n\n**Available `ImType` wrappers (for non-nullable types only):**\n\n* `ImNum(double value)` / `ImNum(int value)`\n* `ImString(String value)`\n* `ImBool(bool value)`\n* `ImList(List\u003cImType\u003e value)` or `ImList.wrap(List\u003cdynamic\u003e nativeList)`\n* `ImMap(Map\u003cImType, ImType\u003e value)` or `ImMap.wrap(Map\u003cdynamic, dynamic\u003e nativeMap)`\n\nAn `UnsupportedImTypeException` is thrown if `ImList.wrap` or `ImMap.wrap` encounters a type that cannot be converted.\n\n### Handling Exceptions (Web)\n\nTo ensure custom exceptions are correctly propagated from Web Workers:\n\n1. **Define a Custom IsolateException:** Extend `IsolateException`.\n2. **Register the Exception:** Use `IsolateManager.registerException()` in your main application.\n3. **Throw the Custom Exception:** In your isolate function.\n\n```dart\nimport 'package:isolate_manager/isolate_manager.dart';\n\n// 1. Define your custom exception\nclass MyCustomWebException extends IsolateException {\n  const MyCustomWebException(super.error, [super.stacktrace]);\n\n  @override\n  String get name =\u003e 'MyCustomWebException'; // Crucial for deserialization\n}\n\n@pragma('vm:entry-point')\n@isolateManagerWorker\nImNum taskThatThrowsCustom(ImNum input) {\n  if (input.unwrap == 0) {\n    throw const MyCustomWebException('Input cannot be zero!');\n  }\n  return ImNum(100 / (input.unwrap as num));\n}\n\nvoid main() async {\n  // 2. Register the exception type (typically in your app's initialization)\n  IsolateManager.registerException(\n    (message, stackTrace) =\u003e MyCustomWebException(message, stackTrace),\n  );\n\n  final isolate = IsolateManager.create(\n    taskThatThrowsCustom,\n    workerName: 'taskThatThrowsCustom', // For JS Worker\n  );\n\n  try {\n    print('Trying with valid input...');\n    final result = await isolate.compute(ImNum(10));\n    print('Result: ${(result as ImNum).unwrap}'); // Should be 10\n\n    print('\\nTrying with input that causes custom exception...');\n    await isolate.compute(ImNum(0)); // This will throw\n  } on MyCustomWebException catch (e, s) {\n    print('Caught MyCustomWebException!');\n    print('Error: ${e.error}');\n    // print('Stack: $s'); // s is the stacktrace from the main isolate\n    // print('Original Isolate Stack: ${e.stacktrace}'); // stacktrace from the worker\n  } catch (e) {\n    print('Caught an unexpected error: $e');\n  } finally {\n    await isolate.stop();\n  }\n}\n```\n\n## Add a Worker Mapping Once\n\nTypically done during app initialization:\n\n```dart\nIsolateManager.addWorkerMapping(\n  fibonacciRecursive,      // Dart function\n  'fibonacciRecursive',    // Generated JS-worker file name\n);\nIsolateManager.addWorkerMapping(addNumbersFuture, 'addNumbersFuture');\n```\n\nUse the mapped function:\n\n```dart\n// No boilerplate — the manager already knows which worker to spin up.\nawait IsolateManager.runFunction(fibonacciRecursive, 40);\nawait sharedIsolate.compute(addNumbersFuture, [10.5, 20.3]);\nawait singleFuncIsolate.compute(10);\n```\n\nIf you’re wondering what “magic” was removed:\n\n```dart\n// Long form (now unnecessary):\n// final result = await IsolateManager.run(\n//   () =\u003e fibonacciRecursive(40),\n//   workerName: 'fibonacciRecursive',\n//   workerParameter: 40,\n// );\n```\n\n## Web Worker Generator\n\nUse the `isolate_manager:generate` command to compile annotated Dart functions into JavaScript workers for web deployment.\nSee [Web (JavaScript Workers)](#web-javascript-workers) for web platform setup.\n\n**Command:**\n\n```shell\ndart run isolate_manager:generate\n```\n\n**Flags \u0026 Options:**\n\n* `--single`: Generate only for functions annotated with `@isolateManagerWorker`.\n* `--shared`: Generate only for functions annotated with `@isolateManagerSharedWorker`.\n* `--in \u003cpath\u003e` (or `-i \u003cpath\u003e`): Specify the input directory to scan for annotated functions (default: `lib`).\n* `--out \u003cpath\u003e` (or `-o \u003cpath\u003e`): Specify the output directory for generated JS files (default: `web`).\n* `--obfuscate \u003clevel\u003e`: Set JavaScript obfuscation level (0-4, default is 4 for smallest size). 0 means no obfuscation.\n* `--debug`: Retain temporary files created during generation for debugging purposes.\n* `--worker-mappings-experiment=lib/main.dart` (Experimental): Attempt to auto-generate `workerMappings` for `IsolateManager.createShared` by scanning the specified Dart file.\n\n## Additional Tips\n\n* **Queue Length:** Check `isolateManagerInstance.queuesLength` to get the current number of tasks in the queue.\n* **Manual Start Control:** Use `isolateManagerInstance.ensureStarted()` to await explicit initialization if needed. Check `isolateManagerInstance.isStarted` to see if the isolate is ready.\n* **Data Flow with Converters (WASM):** When WASM type converters are active, the data flow is: Main Isolate → Worker → Main Isolate → Converter → Final Result.\n\n## Performance Benchmark\n\nThe following benchmarks demonstrate the performance of recursive Fibonacci calculations across different concurrency approaches and environments. Measurements are in microseconds (µs) on a MacBook M1 Pro 14\" with 16GB RAM.\n\n* **VM (Native)**\n\n| Fibonacci |  Main App | One Isolate | Three Isolates | IsolateManager.runFunction | IsolateManager.run | Isolate.run |\n| :-------: | --------: | ----------: | -------------: | -------------------------: | -----------------: | ----------: |\n|     30    |   551,928 |     541,882 |        195,646 |                    553,949 |            547,982 |     538,820 |\n|     33    | 2,273,956 |   2,268,299 |        816,148 |                  2,288,071 |          2,282,269 |   2,271,376 |\n|     36    | 9,761,067 |   9,669,422 |      3,453,328 |                  9,643,678 |          9,606,443 |   9,648,076 |\n\n* **Chrome (with Worker support, JS compiler)**\n\n| Fibonacci |   Main App | One Isolate | Three Isolates | IsolateManager.runFunction | IsolateManager.run | Isolate.run (Unsupported) |\n| :-------: | ---------: | ----------: | -------------: | -------------------------: | -----------------: | ------------------------: |\n|     30    |  2,274,100 |     573,900 |        211,700 |                  1,160,800 |          1,181,800 |                         0 |\n|     33    |  9,493,100 |   2,330,900 |        821,400 |                  2,860,800 |          2,866,300 |                         0 |\n|     36    | 40,051,000 |   9,756,200 |      3,452,100 |                 10,281,200 |         10,270,300 |                         0 |\n\n* **Chrome (with Worker support, WASM compiler)**\n\n| Fibonacci |  Main App | One Isolate | Three Isolates | IsolateManager.runFunction | IsolateManager.run | Isolate.run (Unsupported) |\n| :-------: | --------: | ----------: | -------------: | -------------------------: | -----------------: | ------------------------: |\n|     30    |   242,701 |     552,800 |        200,300 |                  1,099,100 |          1,081,800 |                         0 |\n|     33    | 1,027,300 |   2,315,700 |        819,800 |                  2,863,700 |          2,852,600 |                         0 |\n|     36    | 4,396,300 |   9,709,700 |      3,446,300 |                 10,284,000 |         10,375,800 |                         0 |\n\nFor more details, see the [full benchmark information](https://github.com/lamnhan066/isolate_manager/tree/main/benchmark).\n\n## Contributing\n\nContributions, issues, and feature requests are welcome! Feel free to check the [issues page](https://github.com/lamnhan066/isolate_manager/issues).\n\nIf you find this package helpful, consider supporting the developer:\n\n[![BMC QR](https://raw.githubusercontent.com/lamnhan066/isolate_manager/main/assets/images/bmc_qr.png)](https://www.buymeacoffee.com/lamnhan066)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flamnhan066%2Fisolate_manager","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flamnhan066%2Fisolate_manager","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flamnhan066%2Fisolate_manager/lists"}