Skip to content

An open-source cross-platform alternative to AirDrop

refactor: extract to typed_isolates

Tien Do Nam8ad91ddea26a
diff --git a/common/lib/src/isolate/child/http_scan_discovery_isolate.dart b/common/lib/src/isolate/child/http_scan_discovery_isolate.dart
index e66ab61c..ed1d297a 100644
--- a/common/lib/src/isolate/child/http_scan_discovery_isolate.dart
+++ b/common/lib/src/isolate/child/http_scan_discovery_isolate.dart
@@ -1,10 +1,9 @@
import 'package:common/model/device.dart';
import 'package:common/src/isolate/child/main.dart';
-import 'package:common/src/isolate/dto/isolate_task.dart';
-import 'package:common/src/isolate/dto/isolate_task_result.dart';
import 'package:common/src/isolate/dto/send_to_isolate_data.dart';
import 'package:common/src/task/discovery/http_scan_discovery.dart';
import 'package:meta/meta.dart';
+import 'package:typed_isolates/typed_isolates.dart';
sealed class HttpScanTask {}
diff --git a/common/lib/src/isolate/child/upload_isolate.dart b/common/lib/src/isolate/child/upload_isolate.dart
index 61ecbc7d..ea1fe1cd 100644
--- a/common/lib/src/isolate/child/upload_isolate.dart
+++ b/common/lib/src/isolate/child/upload_isolate.dart
@@ -4,13 +4,12 @@ import 'dart:typed_data';
import 'package:common/isolate.dart';
import 'package:common/model/device.dart';
import 'package:common/src/isolate/child/main.dart';
-import 'package:common/src/isolate/dto/isolate_task.dart';
-import 'package:common/src/isolate/dto/isolate_task_result.dart';
import 'package:common/src/isolate/dto/send_to_isolate_data.dart';
import 'package:common/src/task/upload/http_upload.dart';
import 'package:common/util/stream.dart';
import 'package:meta/meta.dart';
import 'package:refena/refena.dart';
+import 'package:typed_isolates/typed_isolates.dart';
sealed class BaseHttpUploadTask {}
diff --git a/common/lib/src/isolate/parent/actions.dart b/common/lib/src/isolate/parent/actions.dart
index 5b4f9b2c..014ae942 100644
--- a/common/lib/src/isolate/parent/actions.dart
+++ b/common/lib/src/isolate/parent/actions.dart
@@ -4,15 +4,11 @@ import 'package:common/model/device.dart';
import 'package:common/src/isolate/child/http_scan_discovery_isolate.dart';
import 'package:common/src/isolate/child/multicast_discovery_isolate.dart';
import 'package:common/src/isolate/child/upload_isolate.dart';
-import 'package:common/src/isolate/dto/isolate_task.dart';
-import 'package:common/src/isolate/dto/isolate_task_result.dart';
import 'package:common/src/isolate/dto/send_to_isolate_data.dart';
import 'package:common/src/isolate/parent/parent_isolate_provider.dart';
-import 'package:common/src/util/id_provider.dart';
-import 'package:common/src/util/isolate_helper.dart';
import 'package:refena/refena.dart';
-
-final _idProvider = IdProvider();
+import 'package:typed_isolates/id.dart';
+import 'package:typed_isolates/typed_isolates.dart';
class IsolateInterfaceHttpDiscoveryAction extends ReduxActionWithResult<IsolateController, ParentIsolateState, Stream<Device>> {
final String networkInterface;
@@ -40,9 +36,8 @@ class IsolateInterfaceHttpDiscoveryAction extends ReduxActionWithResult<IsolateC
return (
state,
- _sendTaskAndListenStream(
+ connection.sendWrappedTaskAndListenStream(
task: task,
- connection: connection,
)
);
}
@@ -71,9 +66,8 @@ class IsolateFavoriteHttpDiscoveryAction extends ReduxActionWithResult<IsolateCo
return (
state,
- _sendTaskAndListenStream(
+ connection.sendWrappedTaskAndListenStream(
task: task,
- connection: connection,
)
);
}
@@ -161,10 +155,9 @@ class IsolateHttpUploadAction extends ReduxActionWithResult<IsolateController, P
device: device,
);
- final taskId = _idProvider.getNextId();
- final progress = _sendTaskAndListenStream(
+ final taskId = IdProvider.instance.getNextId();
+ final progress = connection.sendWrappedTaskAndListenStream(
task: task,
- connection: connection,
taskId: taskId,
);
@@ -194,7 +187,6 @@ class IsolateHttpUploadCancelAction extends ReduxAction<IsolateController, Paren
connection.sendToIsolate(SendToIsolateData(
syncState: null,
data: IsolateTask(
- id: _idProvider.getNextId(),
data: HttpUploadCancelTask(
taskId: taskId,
),
@@ -205,52 +197,28 @@ class IsolateHttpUploadCancelAction extends ReduxAction<IsolateController, Paren
}
}
-/// Sends a task to the isolate
-/// and transforms [IsolateTaskStreamResult] into a proper stream making it easier to work with.
-Stream<R> _sendTaskAndListenStream<R, T>({
- required T task,
- required IsolateConnector<IsolateTaskStreamResult<R>, SendToIsolateData<IsolateTask<T>>> connection,
- int? taskId,
-}) {
- final wrappedTask = IsolateTask(
- id: taskId ?? _idProvider.getNextId(),
- data: task,
- );
-
- // ignore: discarded_futures
- Future.microtask(() {
- connection.sendToIsolate(SendToIsolateData<IsolateTask<T>>(
- syncState: null,
- data: wrappedTask,
- ));
- });
-
- return _convertResponseToStream<R, T>(
- taskId: wrappedTask.id,
- connection: connection,
- );
-}
+/// Adds the [SendToIsolateData] envelope on top of the generic
+/// [IsolateTaskConnector.sendTaskAndListenStream] from `typed_isolates`.
+extension _WrappedTaskConnector<R, T> on IsolateConnector<IsolateTaskStreamResult<R>, SendToIsolateData<IsolateTask<T>>> {
+ /// Sends a [task] wrapped in a [SendToIsolateData] envelope and transforms
+ /// the responded [IsolateTaskStreamResult]s into a plain [Stream].
+ Stream<R> sendWrappedTaskAndListenStream({
+ required T task,
+ int? taskId,
+ }) {
+ final wrappedTask = IsolateTask(
+ id: taskId,
+ data: task,
+ );
-Stream<R> _convertResponseToStream<R, T>({
- required int taskId,
- required IsolateConnector<IsolateTaskStreamResult<R>, SendToIsolateData<IsolateTask<T>>> connection,
-}) {
- final controller = StreamController<R>();
- late StreamSubscription subscription;
- subscription = connection.receiveFromIsolate.listen((result) {
- if (result.id == taskId) {
- if (result.data != null) {
- controller.add(result.data as R);
- } else if (result.done) {
- if (result.error != null) {
- controller.addError(result.error!);
- } else {
- subscription.cancel(); // ignore: discarded_futures
- controller.close(); // ignore: discarded_futures
- }
- }
- }
- });
+ // ignore: discarded_futures
+ Future.microtask(() {
+ sendToIsolate(SendToIsolateData(
+ syncState: null,
+ data: wrappedTask,
+ ));
+ });
- return controller.stream;
+ return convertResponseToStream(taskId: wrappedTask.id);
+ }
}
diff --git a/common/lib/src/isolate/parent/parent_isolate_provider.dart b/common/lib/src/isolate/parent/parent_isolate_provider.dart
index b2ae55c8..c15d6ca5 100644
--- a/common/lib/src/isolate/parent/parent_isolate_provider.dart
+++ b/common/lib/src/isolate/parent/parent_isolate_provider.dart
@@ -4,13 +4,11 @@ import 'package:common/src/isolate/child/main.dart';
import 'package:common/src/isolate/child/multicast_discovery_isolate.dart';
import 'package:common/src/isolate/child/sync_provider.dart';
import 'package:common/src/isolate/child/upload_isolate.dart';
-import 'package:common/src/isolate/dto/isolate_task.dart';
-import 'package:common/src/isolate/dto/isolate_task_result.dart';
import 'package:common/src/isolate/dto/send_to_isolate_data.dart';
-import 'package:common/src/util/isolate_helper.dart';
import 'package:dart_mappable/dart_mappable.dart';
import 'package:logging/logging.dart';
import 'package:refena/refena.dart';
+import 'package:typed_isolates/typed_isolates.dart';
part 'parent_isolate_provider.mapper.dart';
@@ -74,7 +72,7 @@ class IsolateSetupAction extends AsyncReduxAction<IsolateController, ParentIsola
@override
Future<ParentIsolateState> reduce() async {
- final httpScanDiscovery = await startIsolate<IsolateTaskStreamResult<Device>, SendToIsolateData<IsolateTask<HttpScanTask>>, InitialData>(
+ final httpScanDiscovery = await TypedIsolates.startIsolate<IsolateTaskStreamResult<Device>, SendToIsolateData<IsolateTask<HttpScanTask>>, InitialData>(
task: setupHttpScanDiscoveryIsolate,
param: InitialData(
syncState: state.syncState,
@@ -82,7 +80,7 @@ class IsolateSetupAction extends AsyncReduxAction<IsolateController, ParentIsola
),
);
- final multicastDiscovery = await startIsolate<Device, SendToIsolateData<MulticastTask>, InitialData>(
+ final multicastDiscovery = await TypedIsolates.startIsolate<Device, SendToIsolateData<MulticastTask>, InitialData>(
task: setupMulticastDiscoveryIsolate,
param: InitialData(
syncState: state.syncState,
@@ -93,7 +91,7 @@ class IsolateSetupAction extends AsyncReduxAction<IsolateController, ParentIsola
final httpUploadIsolates = List.generate(
_uploadIsolateCount,
(index) async {
- final httpUpload = await startIsolate<IsolateTaskStreamResult<double>, SendToIsolateData<IsolateTask<BaseHttpUploadTask>>, InitialData>(
+ final httpUpload = await TypedIsolates.startIsolate<IsolateTaskStreamResult<double>, SendToIsolateData<IsolateTask<BaseHttpUploadTask>>, InitialData>(
task: setupHttpUploadIsolate,
param: InitialData(
syncState: state.syncState,
diff --git a/common/pubspec.yaml b/common/pubspec.yaml
index d55d7428..4fd01cf6 100644
--- a/common/pubspec.yaml
+++ b/common/pubspec.yaml
@@ -13,6 +13,8 @@ dependencies:
meta: ^1.9.1
mime: ^2.0.0
refena: ^3.1.0
+ typed_isolates:
+ path: ../packages/typed_isolates
dev_dependencies:
build_runner: ^2.4.7
diff --git a/packages/typed_isolates/.gitignore b/packages/typed_isolates/.gitignore
new file mode 100644
index 00000000..bf71f4de
--- /dev/null
+++ b/packages/typed_isolates/.gitignore
@@ -0,0 +1,7 @@
+# https://dart.dev/tools/private-files
+# Created by `dart pub`
+.dart_tool/
+
+# Avoid committing pubspec.lock for library packages; see
+# https://dart.dev/tools/pub/private-files#pubspec-lock.
+pubspec.lock
diff --git a/packages/typed_isolates/LICENSE b/packages/typed_isolates/LICENSE
new file mode 100644
index 00000000..286c97fe
--- /dev/null
+++ b/packages/typed_isolates/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2026 Tien Do Nam
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/packages/typed_isolates/README.md b/packages/typed_isolates/README.md
new file mode 100644
index 00000000..1a5bde4e
--- /dev/null
+++ b/packages/typed_isolates/README.md
@@ -0,0 +1,86 @@
+# typed_isolates
+
+Create isolates and communicate with them in a **type-safe** manner.
+
+Dart's raw `Isolate` / `SendPort` API is untyped — every message is `dynamic`.
+This package wraps the boilerplate and gives you a connector with statically-typed
+send and receive channels.
+
+## Concept
+
+Three type parameters describe the isolate:
+
+- `R` — the type of messages the main isolate **receives** from the child.
+- `S` — the type of messages the main isolate **sends** to the child.
+- `P` — the type of the parameter passed to the child on startup.
+
+## Usage
+
+Spawn an isolate with `TypedIsolates.startIsolate`. It returns an
+`IsolateConnector<R, S>` for talking to the child.
+
+```dart
+import 'package:typed_isolates/typed_isolates.dart';
+
+Future<void> main() async {
+ // R = int (received), S = String (sent), P = String (start param)
+ final connector = await TypedIsolates.startIsolate<int, String, String>(
+ param: 'greeting',
+ task: _childTask,
+ );
+
+ // Listen to messages coming back from the isolate.
+ connector.receiveFromIsolate.listen((value) {
+ print('main received: $value');
+ });
+
+ // Send messages to the isolate.
+ connector.sendToIsolate('hello');
+ connector.sendToIsolate('world');
+
+ // Shut it down when done.
+ await Future.delayed(const Duration(seconds: 1));
+ connector.isolate.kill();
+}
+
+// Runs inside the spawned isolate.
+Future<void> _childTask(
+ Stream<String> receiveFromMain,
+ void Function(int) sendToMain,
+ String param,
+) async {
+ print('child started with param: $param');
+ await for (final message in receiveFromMain) {
+ sendToMain(message.length); // reply with the length of each message
+ }
+}
+```
+
+`IsolateConnector` exposes:
+
+- `receiveFromIsolate` — a broadcast `Stream<R>` of messages from the child.
+- `sendToIsolate(S message)` — send a typed message to the child.
+- `isolate` — the underlying `Isolate` (e.g. call `.kill()` to stop it).
+
+## Request / response tasks
+
+For a request-and-reply pattern (correlating each response with its request),
+the package ships a small set of DTOs you can use as your `S` / `R` payloads:
+
+- `IsolateTask<T>` — a request carrying an `id` and a `data` payload.
+- `IsolateTaskResult<T>` (`IsolateTaskSuccessResult` / `IsolateTaskErrorResult`) —
+ a single response matched to the request `id`.
+- `IsolateTaskStreamResult<T>` — a streamed response (`.event`, `.done`, `.error`)
+ for tasks that emit multiple values over time, plus `IsolateTaskStreamAckResult`
+ to acknowledge receipt of an event.
+
+When your connector sends bare `IsolateTask`s and receives
+`IsolateTaskStreamResult`s, `sendTaskAndListenStream` does the whole round-trip —
+it assigns an id, sends the task, and returns a `Stream` of the results:
+
+```dart
+// connection: IsolateConnector<IsolateTaskStreamResult<int>, IsolateTask<MyTask>>
+final Stream<int> results = connection.sendTaskAndListenStream(
+ task: MyTask('my input'),
+);
+```
diff --git a/packages/typed_isolates/analysis_options.yaml b/packages/typed_isolates/analysis_options.yaml
new file mode 100644
index 00000000..794abcec
--- /dev/null
+++ b/packages/typed_isolates/analysis_options.yaml
@@ -0,0 +1,14 @@
+include: package:lints/recommended.yaml
+
+formatter:
+ trailing_commas: preserve
+ page_width: 150
+
+linter:
+ rules:
+ prefer_single_quotes: true
+ sort_pub_dependencies: true
+ always_use_package_imports: true
+ directives_ordering: true
+ unawaited_futures: true
+ discarded_futures: true
diff --git a/packages/typed_isolates/lib/id.dart b/packages/typed_isolates/lib/id.dart
new file mode 100644
index 00000000..5501b22d
--- /dev/null
+++ b/packages/typed_isolates/lib/id.dart
@@ -0,0 +1 @@
+export 'src/id_provider.dart';
diff --git a/common/lib/src/util/id_provider.dart b/packages/typed_isolates/lib/src/id_provider.dart
similarity index 85%
rename from common/lib/src/util/id_provider.dart
rename to packages/typed_isolates/lib/src/id_provider.dart
index a22ad880..249c2d22 100644
--- a/common/lib/src/util/id_provider.dart
+++ b/packages/typed_isolates/lib/src/id_provider.dart
@@ -1,5 +1,7 @@
/// A simple class that provides an id.
class IdProvider {
+ static IdProvider instance = IdProvider();
+
int _id = 0;
/// Returns the next id.
diff --git a/common/lib/src/util/isolate_helper.dart b/packages/typed_isolates/lib/src/isolate_helper.dart
similarity index 55%
rename from common/lib/src/util/isolate_helper.dart
rename to packages/typed_isolates/lib/src/isolate_helper.dart
index 405ed098..f3d86971 100644
--- a/common/lib/src/util/isolate_helper.dart
+++ b/packages/typed_isolates/lib/src/isolate_helper.dart
@@ -25,46 +25,48 @@ class IsolateConnector<R, S> {
}
}
-/// A helper function to easier work with isolates.
-/// Starts an isolate and setups the [SendPort] and [ReceivePort] to communicate with it.
-///
-/// [R] is the type of the messages that the main isolate will **receive** from the spawned isolate.
-/// [S] is the type of the messages that the main isolate will **send** to the spawned isolate.
-/// [P] is the type of the parameter that is passed to the spawned isolate.
-Future<IsolateConnector<R, S>> startIsolate<R, S, P>({
- required Future<void> Function(Stream<S> receiveFromMain, void Function(R) sendToMain, P param) task,
- required P param,
-}) async {
- final receivePort = ReceivePort();
- final isolate = await Isolate.spawn(
- (param) => _isolateRunner<R, S, P>(param),
- _IsolateParam<R, S, P>(receivePort.sendPort, task, param),
- );
-
- final receiveFromIsolateController = StreamController<R>();
- final sendToIsolateCompleter = Completer<SendPort>();
- receivePort.listen((message) {
- switch (message) {
- case R():
- receiveFromIsolateController.add(message);
- break;
- case SendPort():
- sendToIsolateCompleter.complete(message);
- break;
- default:
- print('Unexpected type when receiving message from isolate: "$message" that has type <${message.runtimeType}> but only <$R> is expected.');
- }
- });
- final sendToIsolate = await sendToIsolateCompleter.future;
-
- // Callback to signal that the [SendPort] is ready
- sendToIsolate.send(_SendToIsolateReceived());
-
- return IsolateConnector._(
- receiveFromIsolateController.stream.asBroadcastStream(),
- sendToIsolate,
- isolate,
- );
+class TypedIsolates {
+ /// A helper function to easier work with isolates.
+ /// Starts an isolate and setups the [SendPort] and [ReceivePort] to communicate with it.
+ ///
+ /// [R] is the type of the messages that the main isolate will **receive** from the spawned isolate.
+ /// [S] is the type of the messages that the main isolate will **send** to the spawned isolate.
+ /// [P] is the type of the parameter that is passed to the spawned isolate.
+ static Future<IsolateConnector<R, S>> startIsolate<R, S, P>({
+ required Future<void> Function(Stream<S> receiveFromMain, void Function(R) sendToMain, P param) task,
+ required P param,
+ }) async {
+ final receivePort = ReceivePort();
+ final isolate = await Isolate.spawn(
+ (param) => _isolateRunner<R, S, P>(param),
+ _IsolateParam<R, S, P>(receivePort.sendPort, task, param),
+ );
+
+ final receiveFromIsolateController = StreamController<R>();
+ final sendToIsolateCompleter = Completer<SendPort>();
+ receivePort.listen((message) {
+ switch (message) {
+ case R():
+ receiveFromIsolateController.add(message);
+ break;
+ case SendPort():
+ sendToIsolateCompleter.complete(message);
+ break;
+ default:
+ print('Unexpected type when receiving message from isolate: "$message" that has type <${message.runtimeType}> but only <$R> is expected.');
+ }
+ });
+ final sendToIsolate = await sendToIsolateCompleter.future;
+
+ // Callback to signal that the [SendPort] is ready
+ sendToIsolate.send(_SendToIsolateReceived());
+
+ return IsolateConnector._(
+ receiveFromIsolateController.stream.asBroadcastStream(),
+ sendToIsolate,
+ isolate,
+ );
+ }
}
class _IsolateParam<R, S, P> {
@@ -114,4 +116,4 @@ Future<void> _isolateRunner<R, S, P>(_IsolateParam<R, S, P> params) async {
(data) => params._sendToMain.send(data),
params.param,
);
-}
+}
\ No newline at end of file
diff --git a/common/lib/src/isolate/dto/isolate_task.dart b/packages/typed_isolates/lib/src/isolate_task.dart
similarity index 76%
rename from common/lib/src/isolate/dto/isolate_task.dart
rename to packages/typed_isolates/lib/src/isolate_task.dart
index 109aabf5..7ff3ea51 100644
--- a/common/lib/src/isolate/dto/isolate_task.dart
+++ b/packages/typed_isolates/lib/src/isolate_task.dart
@@ -1,4 +1,5 @@
-import 'package:common/src/isolate/dto/isolate_task_result.dart';
+import 'package:typed_isolates/src/id_provider.dart';
+import 'package:typed_isolates/src/isolate_task_result.dart';
/// A data structure that can be sent to an isolate.
/// This is used to represent the following schemas:
@@ -15,7 +16,7 @@ class IsolateTask<T> {
final T data;
IsolateTask({
- required this.id,
+ int? id,
required this.data,
- });
+ }) : id = id ?? IdProvider.instance.getNextId();
}
diff --git a/packages/typed_isolates/lib/src/isolate_task_helper.dart b/packages/typed_isolates/lib/src/isolate_task_helper.dart
new file mode 100644
index 00000000..e2ad7f17
--- /dev/null
+++ b/packages/typed_isolates/lib/src/isolate_task_helper.dart
@@ -0,0 +1,63 @@
+import 'dart:async';
+
+import 'package:typed_isolates/src/id_provider.dart';
+import 'package:typed_isolates/src/isolate_helper.dart';
+import 'package:typed_isolates/src/isolate_task.dart';
+import 'package:typed_isolates/src/isolate_task_result.dart';
+
+/// Helpers for connectors whose child isolate replies with
+/// [IsolateTaskStreamResult]s (the request / streamed-response pattern).
+extension IsolateTaskStreamConnector<R, S> on IsolateConnector<IsolateTaskStreamResult<R>, S> {
+ /// Listens to the responses of an already-sent task with [taskId] and
+ /// transforms the [IsolateTaskStreamResult]s into a plain [Stream].
+ Stream<R> convertResponseToStream({
+ required int taskId,
+ }) {
+ final controller = StreamController<R>();
+ late StreamSubscription subscription;
+ subscription = receiveFromIsolate.listen((result) {
+ if (result.id == taskId) {
+ if (result.data != null) {
+ controller.add(result.data as R);
+ } else if (result.done) {
+ if (result.error != null) {
+ controller.addError(result.error!);
+ } else {
+ subscription.cancel(); // ignore: discarded_futures
+ controller.close(); // ignore: discarded_futures
+ }
+ }
+ }
+ });
+
+ return controller.stream;
+ }
+}
+
+/// Helpers for connectors that send bare [IsolateTask]s (no envelope).
+extension IsolateTaskConnector<R, T> on IsolateConnector<IsolateTaskStreamResult<R>, IsolateTask<T>> {
+ /// Sends a [task] to the isolate and transforms the responded
+ /// [IsolateTaskStreamResult]s into a plain [Stream].
+ ///
+ /// The [task] is wrapped in an [IsolateTask] with a unique id (taken from
+ /// [IdProvider.instance], or [taskId] if provided).
+ ///
+ /// If the connector sends a custom envelope instead of a bare [IsolateTask],
+ /// wrap and send the task yourself and use [convertResponseToStream].
+ Stream<R> sendTaskAndListenStream({
+ required T task,
+ int? taskId,
+ }) {
+ final isolateTask = IsolateTask(
+ id: taskId ?? IdProvider.instance.getNextId(),
+ data: task,
+ );
+
+ // ignore: discarded_futures
+ Future.microtask(() {
+ sendToIsolate(isolateTask);
+ });
+
+ return convertResponseToStream(taskId: isolateTask.id);
+ }
+}
diff --git a/common/lib/src/isolate/dto/isolate_task_result.dart b/packages/typed_isolates/lib/src/isolate_task_result.dart
similarity index 96%
rename from common/lib/src/isolate/dto/isolate_task_result.dart
rename to packages/typed_isolates/lib/src/isolate_task_result.dart
index a086e779..b4e6bba9 100644
--- a/common/lib/src/isolate/dto/isolate_task_result.dart
+++ b/packages/typed_isolates/lib/src/isolate_task_result.dart
@@ -1,4 +1,4 @@
-import 'package:common/src/isolate/dto/isolate_task.dart';
+import 'package:typed_isolates/src/isolate_task.dart';
/// The response data structure from an [IsolateTask].
sealed class IsolateTaskResult<T> {
diff --git a/packages/typed_isolates/lib/typed_isolates.dart b/packages/typed_isolates/lib/typed_isolates.dart
new file mode 100644
index 00000000..5af291f7
--- /dev/null
+++ b/packages/typed_isolates/lib/typed_isolates.dart
@@ -0,0 +1,4 @@
+export 'src/isolate_helper.dart';
+export 'src/isolate_task.dart';
+export 'src/isolate_task_helper.dart';
+export 'src/isolate_task_result.dart';
diff --git a/packages/typed_isolates/pubspec.yaml b/packages/typed_isolates/pubspec.yaml
new file mode 100644
index 00000000..91ef7b56
--- /dev/null
+++ b/packages/typed_isolates/pubspec.yaml
@@ -0,0 +1,9 @@
+name: typed_isolates
+description: Create isolates and communicate with them in a type-safe manner.
+version: 1.0.0
+
+environment:
+ sdk: ^3.5.0
+
+dev_dependencies:
+ lints: ^2.0.0