diff --git a/benchmark/benchmark.dart b/benchmark/benchmark.dart index 96520a2..62a5584 100644 --- a/benchmark/benchmark.dart +++ b/benchmark/benchmark.dart @@ -9,19 +9,23 @@ import '../test/isolate_manager_test.dart'; // dart test --platform=chrome "benchmark/benchmark.dart" void main() { - test('benchmark', () async { - print('|Fibonacci|Main App|One Isolate|Three Isolates|Isolate.run|'); - print('|:-:|-:|-:|-:|-:|'); + test( + 'benchmark', + () async { + print('|Fibonacci|Main App|One Isolate|Three Isolates|Isolate.run|'); + print('|:-:|-:|-:|-:|-:|'); - // Fibonacci 30 - await execute(30); + // Fibonacci 30 + await execute(30); - // Fibonacci 33 - await execute(33); + // Fibonacci 33 + await execute(33); - // Fibonacci 36 - await execute(36); - }, timeout: Timeout(Duration(seconds: 120))); + // Fibonacci 36 + await execute(36); + }, + timeout: const Timeout(Duration(seconds: 120)), + ); } Future execute(int fibonacciNumber) async { @@ -65,7 +69,8 @@ Future execute(int fibonacciNumber) async { stopWatch.start(); await Future.wait( - [for (int i = 0; i < 70; i++) threeIsolates.compute(fibonacciNumber)]); + [for (int i = 0; i < 70; i++) threeIsolates.compute(fibonacciNumber)], + ); threeIsolatesInIsolate = stopWatch.elapsed; stopWatch ..stop() @@ -86,5 +91,6 @@ Future execute(int fibonacciNumber) async { } print( - '|$fibonacciNumber|${singleInMain.inMicroseconds}|${singleInIsolate.inMicroseconds}|${threeIsolatesInIsolate.inMicroseconds}|${runMethodInIsolate.inMicroseconds}|'); + '|$fibonacciNumber|${singleInMain.inMicroseconds}|${singleInIsolate.inMicroseconds}|${threeIsolatesInIsolate.inMicroseconds}|${runMethodInIsolate.inMicroseconds}|', + ); } diff --git a/bin/generate_shared.dart b/bin/generate_shared.dart index 15c0c97..c96408e 100644 --- a/bin/generate_shared.dart +++ b/bin/generate_shared.dart @@ -41,9 +41,10 @@ Future generate(ArgResults argResults, List dartArgs) async { final isolateManager = IsolateManager.create( _getAndGenerateFromAnotatedFunctions, concurrent: 3, - )..start(); + ); + await isolateManager.start(); - List> params = []; + final params = >[]; for (final file in allFiles) { if (file is File && file.path.endsWith('.dart')) { final filePath = file.absolute.path; @@ -57,7 +58,7 @@ Future generate(ArgResults argResults, List dartArgs) async { print('Total files to generate: ${params.length}'); - Map anotatedFunctions = {}; + final anotatedFunctions = {}; int counter = 0; await Future.wait( [ @@ -65,7 +66,7 @@ Future generate(ArgResults argResults, List dartArgs) async { isolateManager.compute(param).then((value) { counter += value.length; anotatedFunctions.addAll(value); - }) + }), ], ); @@ -89,8 +90,9 @@ Future generate(ArgResults argResults, List dartArgs) async { } Future> _getAndGenerateFromAnotatedFunctions( - List params) async { - String filePath = params[0]; + List params, +) async { + final String filePath = params[0]; return _getAnotatedFunctions(filePath); } diff --git a/bin/generate_single.dart b/bin/generate_single.dart index daf7025..e9c025a 100644 --- a/bin/generate_single.dart +++ b/bin/generate_single.dart @@ -39,19 +39,21 @@ Future generate(ArgResults argResults, List dartArgs) async { return; } - final List allFiles = _listAllFiles(Directory(input), []); + final allFiles = _listAllFiles(Directory(input), []); final isolateManager = IsolateManager.create( _getAndGenerateFromAnotatedFunctions, concurrent: 3, - )..start(); + ); + await isolateManager.start(); - List> params = []; + final params = >[]; for (final file in allFiles) { if (file is File && file.path.endsWith('.dart')) { final filePath = file.absolute.path; final content = await file.readAsString(); final pattern = RegExp( - '(@$classAnnotation|@$constAnnotation|@$constCustomWorkerAnnotation)'); + '(@$classAnnotation|@$constAnnotation|@$constCustomWorkerAnnotation)', + ); if (content.contains(pattern)) { params.add( [ @@ -71,12 +73,10 @@ Future generate(ArgResults argResults, List dartArgs) async { print('Total files to generate: ${params.length}'); int counter = 0; - await Future.wait( - [ - for (final param in params) - isolateManager.compute(param).then((value) => counter += value) - ], - ); + await Future.wait([ + for (final param in params) + isolateManager.compute(param).then((value) => counter += value), + ]); print('Total generated functions: $counter'); @@ -203,7 +203,8 @@ Future _generateFromAnotatedFunction( sink.writeln('main() {'); if (function.value.isCustomWorker) { sink.writeln( - ' IsolateManagerFunction.customWorkerFunction(${function.key});'); + ' IsolateManagerFunction.customWorkerFunction(${function.key});', + ); } else { sink.writeln(' IsolateManagerFunction.workerFunction(${function.key});'); } @@ -247,7 +248,9 @@ Future _generateFromAnotatedFunction( if (await outputFile.exists()) { print( - 'Path: ${p.relative(sourceFilePath)} => Function: ${function.key} => Compiled: ${p.relative(outputPath)}'); + 'Path: ${p.relative(sourceFilePath)} => ' + 'Function: ${function.key} => Compiled: ${p.relative(outputPath)}', + ); if (!isDebug) { if (isWasm) { await File('$output/$name.unopt.wasm').delete(); @@ -257,7 +260,9 @@ Future _generateFromAnotatedFunction( } } else { print( - 'Path: ${p.relative(sourceFilePath)} => Function: ${function.key} => Compile ERROR: ${p.relative(outputPath)}'); + 'Path: ${p.relative(sourceFilePath)} => Function: ' + '${function.key} => Compile ERROR: ${p.relative(outputPath)}', + ); final r = result.stdout.toString().split('\n'); for (var element in r) { print(' > $element'); diff --git a/lib/src/base/contactor/isolate_contactor/isolate_contactor_stub.dart b/lib/src/base/contactor/isolate_contactor/isolate_contactor_stub.dart index ae94805..7caf964 100644 --- a/lib/src/base/contactor/isolate_contactor/isolate_contactor_stub.dart +++ b/lib/src/base/contactor/isolate_contactor/isolate_contactor_stub.dart @@ -60,8 +60,7 @@ class IsolateContactorInternal extends IsolateContactor { required IsolateConverter workerConverter, bool debugMode = false, }) async { - IsolateContactorInternal isolateContactor = - IsolateContactorInternal._( + final isolateContactor = IsolateContactorInternal._( isolateFunction: isolateFunction, workerName: workerName, isolateParam: initialParams, @@ -81,13 +80,15 @@ class IsolateContactorInternal extends IsolateContactor { _isolateContactorController.onMessage.listen((message) { printDebug(() => 'Message received from Isolate: $message'); _mainStreamController.sink.add(message); - }).onError((err, stack) { + }).onError((Object err, StackTrace stack) { printDebug(() => 'Error message received from Isolate: $err'); _mainStreamController.sink.addError(err, stack); }); _isolate = await Isolate.spawn( - _isolateFunction, [_isolateParam, _receivePort.sendPort]); + _isolateFunction, + [_isolateParam, _receivePort.sendPort], + ); await _isolateContactorController.ensureInitialized.future; printDebug(() => 'Initialized'); @@ -119,16 +120,16 @@ class IsolateContactorInternal extends IsolateContactor { @override Future sendMessage(P message) async { final Completer completer = Completer(); - StreamSubscription? sub; + late final StreamSubscription sub; sub = _isolateContactorController.onMessage.listen((result) async { if (!completer.isCompleted) { completer.complete(result); - await sub?.cancel(); + await sub.cancel(); } }) - ..onError((err, stack) async { + ..onError((Object err, StackTrace stack) async { completer.completeError(err, stack); - await sub?.cancel(); + await sub.cancel(); }); printDebug(() => 'Message send to isolate: $message'); diff --git a/lib/src/base/contactor/isolate_contactor/isolate_contactor_web.dart b/lib/src/base/contactor/isolate_contactor/isolate_contactor_web.dart index e3ea639..4da341e 100644 --- a/lib/src/base/contactor/isolate_contactor/isolate_contactor_web.dart +++ b/lib/src/base/contactor/isolate_contactor/isolate_contactor_web.dart @@ -31,7 +31,8 @@ abstract class IsolateContactorInternal extends IsolateContactor { } catch (_) { if (debugMode) { print( - '[${IsolateContactor.debugLogPrefix}]: This browser doesn\'t support Worker, Future will be applied!'); + '[${IsolateContactor.debugLogPrefix}]: This browser doesn\'t support Worker, Future will be applied!', + ); } } } diff --git a/lib/src/base/contactor/isolate_contactor/web_platform/isolate_contactor_web.dart b/lib/src/base/contactor/isolate_contactor/web_platform/isolate_contactor_web.dart index 0652e9f..cdade56 100644 --- a/lib/src/base/contactor/isolate_contactor/web_platform/isolate_contactor_web.dart +++ b/lib/src/base/contactor/isolate_contactor/web_platform/isolate_contactor_web.dart @@ -34,7 +34,7 @@ class IsolateContactorInternalFuture _workerName = workerName, _isolateParam = isolateParam, _isolateContactorController = IsolateContactorControllerImpl( - StreamController.broadcast(), + StreamController.broadcast(), converter: converter, workerConverter: workerConverter, onDispose: null, @@ -50,8 +50,7 @@ class IsolateContactorInternalFuture required IsolateConverter workerConverter, bool debugMode = false, }) async { - IsolateContactorInternalFuture isolateContactor = - IsolateContactorInternalFuture._( + final isolateContactor = IsolateContactorInternalFuture._( isolateFunction: isolateFunction, workerName: isolateFunctionName, isolateParam: initialParams ?? [], @@ -72,7 +71,7 @@ class IsolateContactorInternalFuture () => '[Main Stream] Message received from Future: $message', ); _mainStreamController.sink.add(message); - }).onError((err, stack) { + }).onError((Object err, StackTrace stack) { printDebug( () => '[Main Stream] Error message received from Future: $err', ); @@ -115,16 +114,16 @@ class IsolateContactorInternalFuture } final Completer completer = Completer(); - StreamSubscription? sub; + late final StreamSubscription sub; sub = _isolateContactorController.onMessage.listen((result) async { if (!completer.isCompleted) { completer.complete(result); - await sub?.cancel(); + await sub.cancel(); } }) - ..onError((err, stack) async { + ..onError((Object err, StackTrace stack) async { completer.completeError(err, stack); - await sub?.cancel(); + await sub.cancel(); }); printDebug(() => 'Message send to isolate: $message'); diff --git a/lib/src/base/contactor/isolate_contactor/web_platform/isolate_contactor_web_worker.dart b/lib/src/base/contactor/isolate_contactor/web_platform/isolate_contactor_web_worker.dart index 8b71519..8e929a7 100644 --- a/lib/src/base/contactor/isolate_contactor/web_platform/isolate_contactor_web_worker.dart +++ b/lib/src/base/contactor/isolate_contactor/web_platform/isolate_contactor_web_worker.dart @@ -57,8 +57,7 @@ class IsolateContactorInternalWorker required IsolateConverter workerConverter, bool debugMode = false, }) async { - IsolateContactorInternalWorker isolateContactor = - IsolateContactorInternalWorker._( + final isolateContactor = IsolateContactorInternalWorker._( isolateFunction: isolateFunction, workerName: workerName, isolateParam: initialParams, @@ -79,7 +78,7 @@ class IsolateContactorInternalWorker () => '[Main Stream] Message received from Worker: $message', ); _mainStreamController.sink.add(message); - }).onError((err, stack) { + }).onError((Object err, StackTrace stack) { printDebug( () => '[Main Stream] Error message received from Worker: $err', ); @@ -122,16 +121,16 @@ class IsolateContactorInternalWorker } final Completer completer = Completer(); - StreamSubscription? sub; + late final StreamSubscription sub; sub = _isolateContactorController!.onMessage.listen((result) async { if (!completer.isCompleted) { completer.complete(result); - await sub?.cancel(); + await sub.cancel(); } }) - ..onError((err, stack) async { + ..onError((Object err, StackTrace stack) async { completer.completeError(err, stack); - await sub?.cancel(); + await sub.cancel(); }); printDebug(() => 'Message send to isolate: $message'); diff --git a/lib/src/base/contactor/isolate_contactor_controller.dart b/lib/src/base/contactor/isolate_contactor_controller.dart index a8df6e1..37a41ea 100644 --- a/lib/src/base/contactor/isolate_contactor_controller.dart +++ b/lib/src/base/contactor/isolate_contactor_controller.dart @@ -16,7 +16,7 @@ abstract class IsolateContactorController { /// `params` is the default parameters of the isolate function. dynamic params, { /// `onDispose` is called when the controller is disposed. - Function()? onDispose, + void Function()? onDispose, }) { // This method is not used in this controller R converter(dynamic value) => value; diff --git a/lib/src/base/contactor/isolate_contactor_controller/isolate_contactor_controller_stub.dart b/lib/src/base/contactor/isolate_contactor_controller/isolate_contactor_controller_stub.dart index 56a2a9d..56b8c11 100644 --- a/lib/src/base/contactor/isolate_contactor_controller/isolate_contactor_controller_stub.dart +++ b/lib/src/base/contactor/isolate_contactor_controller/isolate_contactor_controller_stub.dart @@ -10,8 +10,8 @@ import '../models/exception.dart'; class IsolateContactorControllerImpl implements IsolateContactorController { - final IsolateChannel _delegate; - StreamSubscription? _delegateSubscription; + final IsolateChannel> _delegate; + late final StreamSubscription> _delegateSubscription; final StreamController _mainStreamController = StreamController.broadcast(); @@ -35,7 +35,7 @@ class IsolateContactorControllerImpl : IsolateChannel.connectReceive(params), _initialParams = params is List ? params.first : null { _delegateSubscription = _delegate.stream.listen((event) { - (event as Map).forEach((key, value) { + event.forEach((key, value) { switch (key) { case IsolatePort.main: if (value is IsolateException) { @@ -103,7 +103,7 @@ class IsolateContactorControllerImpl @override Future close() async { await Future.wait([ - _delegateSubscription!.cancel(), + _delegateSubscription.cancel(), _mainStreamController.close(), _isolateStreamController.close(), ]); diff --git a/lib/src/base/contactor/isolate_contactor_controller/web_platform/isolate_contactor_controller_web.dart b/lib/src/base/contactor/isolate_contactor_controller/web_platform/isolate_contactor_controller_web.dart index ac478e0..91f45c3 100644 --- a/lib/src/base/contactor/isolate_contactor_controller/web_platform/isolate_contactor_controller_web.dart +++ b/lib/src/base/contactor/isolate_contactor_controller/web_platform/isolate_contactor_controller_web.dart @@ -9,7 +9,7 @@ import '../isolate_contactor_controller_web.dart'; class IsolateContactorControllerImplFuture implements IsolateContactorControllerImpl { - final StreamController _delegate; + final StreamController _delegate; final StreamController _mainStreamController = StreamController.broadcast(); @@ -65,7 +65,7 @@ class IsolateContactorControllerImplFuture /// Get this StreamController @override - StreamController get controller => _delegate; + StreamController get controller => _delegate; /// Get initial params for `createCustom` @override diff --git a/lib/src/base/contactor/isolate_contactor_controller/web_platform/isolate_contactor_controller_web_worker.dart b/lib/src/base/contactor/isolate_contactor_controller/web_platform/isolate_contactor_controller_web_worker.dart index 727cbb1..f26fe04 100644 --- a/lib/src/base/contactor/isolate_contactor_controller/web_platform/isolate_contactor_controller_web_worker.dart +++ b/lib/src/base/contactor/isolate_contactor_controller/web_platform/isolate_contactor_controller_web_worker.dart @@ -51,7 +51,9 @@ class IsolateContactorControllerImplWorker if (IsolateException.isValidObject(data)) { final exception = IsolateException.fromJson(data); _mainStreamController.addError( - exception.error.toString(), StackTrace.empty); + exception.error.toString(), + StackTrace.empty, + ); return; } diff --git a/lib/src/base/contactor/models/exception.dart b/lib/src/base/contactor/models/exception.dart index 8153b23..cd5bb69 100644 --- a/lib/src/base/contactor/models/exception.dart +++ b/lib/src/base/contactor/models/exception.dart @@ -18,13 +18,15 @@ class IsolateException implements Exception { r'$IsolateException': { 'error': error.toString(), 'stack': stack.toString(), - } + }, }); /// Convert from JSON. factory IsolateException.fromJson(dynamic json) { - assert(isValidObject(json), - 'json should be checked by `isValidObject` before using'); + assert( + isValidObject(json), + 'json should be checked by `isValidObject` before using', + ); final decoded = jsonDecode(json.toString()); final values = decoded[r'$IsolateException']; diff --git a/lib/src/base/shared/function.dart b/lib/src/base/shared/function.dart index 3f670bb..2357716 100644 --- a/lib/src/base/shared/function.dart +++ b/lib/src/base/shared/function.dart @@ -10,7 +10,7 @@ Future internalFunction(List params) async { assert(params.length == 2, 'params must have only 2 elements'); assert(params[0] is Function, 'params[0] is not a Function'); - Completer completer = Completer(); + final completer = Completer(); completer.complete((params[0] as Function)(params[1])); return completer.future; } diff --git a/lib/src/isolate_manager.dart b/lib/src/isolate_manager.dart index cad31c3..707be77 100644 --- a/lib/src/isolate_manager.dart +++ b/lib/src/isolate_manager.dart @@ -179,6 +179,7 @@ class IsolateManager { /// Controller for stream. final StreamController _streamController = StreamController.broadcast(); StreamSubscription? _streamSubscription; + // final List> _streamSubscriptions = []; /// Is the `start` method is starting. @@ -189,11 +190,13 @@ class IsolateManager { /// A default function for using the [IsolateManager.create] method. static void _defaultIsolateFunction(dynamic params) { - IsolateManagerFunction.customFunction(params, - onEvent: (controller, message) { - final function = controller.initialParams; - return function(message); - }); + IsolateManagerFunction.customFunction( + params, + onEvent: (controller, message) { + final function = controller.initialParams; + return function(message); + }, + ); } /// Initialize the instance. This method can be called manually or will be @@ -213,34 +216,30 @@ class IsolateManager { if (isCustomIsolate) { // Create the custom isolates. - await Future.wait( - [ - for (int i = 0; i < concurrent; i++) - IsolateContactor.createCustom( - isolateFunction as IsolateCustomFunction, - workerName: workerName, - initialParams: initialParams, - converter: converter, - workerConverter: workerConverter, - debugMode: isDebug, - ).then((value) => _isolates.addAll({value: false})) - ], - ); + await Future.wait([ + for (int i = 0; i < concurrent; i++) + IsolateContactor.createCustom( + isolateFunction as IsolateCustomFunction, + workerName: workerName, + initialParams: initialParams, + converter: converter, + workerConverter: workerConverter, + debugMode: isDebug, + ).then((value) => _isolates.addAll({value: false})), + ]); } else { // Create isolates with the internal method. - await Future.wait( - [ - for (int i = 0; i < concurrent; i++) - IsolateContactor.createCustom( - _defaultIsolateFunction, - initialParams: isolateFunction as IsolateFunction, - workerName: workerName, - converter: converter, - workerConverter: workerConverter, - debugMode: isDebug, - ).then((value) => _isolates.addAll({value: false})) - ], - ); + await Future.wait([ + for (int i = 0; i < concurrent; i++) + IsolateContactor.createCustom( + _defaultIsolateFunction, + initialParams: isolateFunction as IsolateFunction, + workerName: workerName, + converter: converter, + workerConverter: workerConverter, + debugMode: isDebug, + ).then((value) => _isolates.addAll({value: false})), + ]); } _streamSubscription = _streamController.stream.listen((result) { @@ -260,10 +259,11 @@ class IsolateManager { _isStarting = false; _startedCompleter = Completer(); queueStrategy.clear(); - await Future.wait( - [for (IsolateContactor isolate in _isolates.keys) isolate.dispose()]); + await Future.wait([ + for (final isolate in _isolates.keys) isolate.dispose(), + ]); _isolates.clear(); - _streamSubscription?.cancel(); + await _streamSubscription?.cancel(); } /// Stop the isolate. @@ -310,13 +310,19 @@ class IsolateManager { /// return true; /// }); /// ``` - Future call(P params, - {IsolateCallback? callback, bool priority = false}) => + Future call( + P params, { + IsolateCallback? callback, + bool priority = false, + }) => compute(params, callback: callback, priority: priority); /// Similar to the [compute], for who's using IsolateContactor. - Future sendMessage(P params, - {IsolateCallback? callback, bool priority = false}) => + Future sendMessage( + P params, { + IsolateCallback? callback, + bool priority = false, + }) => compute(params, callback: callback, priority: priority); /// Compute isolate manager with [R] is return type. @@ -351,8 +357,11 @@ class IsolateManager { /// return true; /// }); /// ``` - Future compute(P params, - {IsolateCallback? callback, bool priority = false}) async { + Future compute( + P params, { + IsolateCallback? callback, + bool priority = false, + }) async { await start(); final queue = IsolateQueue(params, callback); @@ -384,32 +393,37 @@ class IsolateManager { } Future _excuteWithCallback( - IsolateContactor isolate, IsolateQueue queue) async { + IsolateContactor isolate, + IsolateQueue queue, + ) async { // Mark the current isolate as busy. _isolates[isolate] = true; - StreamSubscription? sub; - sub = isolate.onMessage.listen((event) async { - // Callbacks on every event. - final completer = Completer(); - completer.complete(queue.callback!(event)); - if (await completer.future) { - sub?.cancel(); + late final StreamSubscription sub; + sub = isolate.onMessage.listen( + (event) async { + // Callbacks on every event. + final completer = Completer(); + completer.complete(queue.callback!(event)); + if (await completer.future) { + await sub.cancel(); + // Mark the current isolate as free. + _isolates[isolate] = false; + // Send the result back to the main app. + _streamController.sink.add(event); + queue.completer.complete(event); + } + }, + onError: (Object error, StackTrace stackTrace) { + sub.cancel(); // Mark the current isolate as free. _isolates[isolate] = false; - // Send the result back to the main app. - _streamController.sink.add(event); - queue.completer.complete(event); - } - }, onError: (error, stackTrace) { - sub?.cancel(); - // Mark the current isolate as free. - _isolates[isolate] = false; - // Send the exception back to the main app. - _streamController.sink.addError(error!, stackTrace); - queue.completer.completeError(error, stackTrace); - }); + // Send the exception back to the main app. + _streamController.sink.addError(error, stackTrace); + queue.completer.completeError(error, stackTrace); + }, + ); try { await isolate.sendMessage(queue.params); @@ -421,26 +435,30 @@ class IsolateManager { } Future _excuteWithoutCallback( - IsolateContactor isolate, IsolateQueue queue) async { + IsolateContactor isolate, + IsolateQueue queue, + ) async { // Mark the current isolate as busy. _isolates[isolate] = true; // Send the `param` to the isolate and wait for the result. - isolate.sendMessage(queue.params).then((value) { - // Mark the current isolate as free. - _isolates[isolate] = false; - - // Send the result back to the main app. - _streamController.sink.add(value); - queue.completer.complete(value); - }).onError((error, stackTrace) { - // Mark the current isolate as free. - _isolates[isolate] = false; - - // Send the exception back to the main app. - _streamController.sink.addError(error!, stackTrace); - queue.completer.completeError(error, stackTrace); - }); + unawaited( + isolate.sendMessage(queue.params).then((value) { + // Mark the current isolate as free. + _isolates[isolate] = false; + + // Send the result back to the main app. + _streamController.sink.add(value); + queue.completer.complete(value); + }).onError((error, stackTrace) { + // Mark the current isolate as free. + _isolates[isolate] = false; + + // Send the exception back to the main app. + _streamController.sink.addError(error!, stackTrace); + queue.completer.completeError(error, stackTrace); + }), + ); return queue.completer.future; } diff --git a/lib/src/isolate_manager_controller.dart b/lib/src/isolate_manager_controller.dart index 08dd45e..e5cb11f 100644 --- a/lib/src/isolate_manager_controller.dart +++ b/lib/src/isolate_manager_controller.dart @@ -34,7 +34,7 @@ class IsolateManagerController { Future close() => _delegate.close(); /// Get initial parameters when you create the IsolateManager. - get initialParams => _delegate.initialParams; + dynamic get initialParams => _delegate.initialParams; /// This parameter is only used for Isolate. Use to listen for values from the main application. Stream

get onIsolateMessage => _delegate.onIsolateMessage; diff --git a/lib/src/isolate_manager_controller/web.dart b/lib/src/isolate_manager_controller/web.dart index a4ff4c1..44f2649 100644 --- a/lib/src/isolate_manager_controller/web.dart +++ b/lib/src/isolate_manager_controller/web.dart @@ -40,7 +40,7 @@ class IsolateManagerControllerImpl /// Get initial parameters when you create the IsolateManager. @override - get initialParams => _delegate.initialParams; + dynamic get initialParams => _delegate.initialParams; /// This parameter is only used for Isolate. Use to listen for values from the main application. @override diff --git a/lib/src/isolate_manager_function.dart b/lib/src/isolate_manager_function.dart index c6bfaa5..a519ff2 100644 --- a/lib/src/isolate_manager_function.dart +++ b/lib/src/isolate_manager_function.dart @@ -9,17 +9,22 @@ import 'isolate_worker/isolate_worker_web.dart' /// A callback for the [IsolateManagerFunction.customFunction] that will be executed only one time /// before all events. typedef IsolateOnInitialCallback = FutureOr Function( - IsolateManagerController controller, T initialParams); + IsolateManagerController controller, + T initialParams, +); /// A callback for the [IsolateManagerFunction.customFunction] that will be executed only one time /// before all events. typedef IsolateOnDisposeCallback = void Function( - IsolateManagerController controller); + IsolateManagerController controller, +); /// A callback for the [IsolateManagerFunction.customFunction] that will be executed every time /// the [message] is received from the `sendMessage` or `execute` method. typedef IsolateOnEventCallback = FutureOr Function( - IsolateManagerController controller, P message); + IsolateManagerController controller, + P message, +); /// A function for the `IsolateManagerFunction.workerFunction`. typedef IsolateWorkerFunction = FutureOr Function(P message); @@ -90,11 +95,11 @@ class IsolateManagerFunction { // Listen to messages received from the main isolate; this code will be called each time // you use `compute` or `sendMessage`. controller.onIsolateMessage.listen((message) { - final completer = Completer(); + final completer = Completer(); completer.future.then( (value) => autoHandleResult ? controller.sendResult(value) : null, onError: autoHandleException - ? (err, stack) => + ? (Object err, StackTrace stack) => controller.sendResultError(IsolateException(err, stack)) : null, ); diff --git a/lib/src/isolate_worker/isolate_worker_web.dart b/lib/src/isolate_worker/isolate_worker_web.dart index be07404..a7a88ee 100644 --- a/lib/src/isolate_worker/isolate_worker_web.dart +++ b/lib/src/isolate_worker/isolate_worker_web.dart @@ -19,10 +19,10 @@ Future isolateWorkerImpl( await completer.future; } controller.onIsolateMessage.listen((message) { - final completer = Completer(); + final completer = Completer(); completer.future.then( - (value) => controller.sendResult(value), - onError: (err, stack) => + controller.sendResult, + onError: (Object err, StackTrace stack) => controller.sendResultError(IsolateException(err, stack)), ); try { diff --git a/test/isolate_manager_shared_test.dart b/test/isolate_manager_shared_test.dart index ce704d5..72c1ac3 100644 --- a/test/isolate_manager_shared_test.dart +++ b/test/isolate_manager_shared_test.dart @@ -44,10 +44,10 @@ void main() async { for (int i = 0; i < 10; i++) isolates.compute(concat, ['$i', '$i']).then((value) { expect(value, equals(concat(['$i', '$i']))); - }) + }), ]); - // Stop the usolate after 5 seconds + // Stop the isolates await isolates.stop(); }); @@ -87,7 +87,7 @@ void main() async { }), ]); - // Stop the usolate after 5 seconds + // Stop the isolates await isolates.stop(); }); @@ -99,7 +99,7 @@ void main() async { // Catch the error from the stream isolates.stream.listen((result) { // print('Stream get add: $result'); - }).onError((e) { + }).onError((Object e) { // print('Error from stream: $e'); expect(e.toString(), equals(ArgumentError().toString())); }); @@ -115,8 +115,8 @@ void main() async { expect(e.toString(), equals(ArgumentError().toString())); } - // Stop the usolate after 5 seconds - await Future.delayed(Duration(seconds: 3)); + // Stop the isolate after 3 seconds + await Future.delayed(const Duration(seconds: 3)); await isolates.stop(); }); @@ -164,7 +164,7 @@ void main() async { final result = await isolates.compute( complexReturn, >[ - ['abc'] + ['abc'], ], ); @@ -172,12 +172,13 @@ void main() async { expect(result, isA>>()); expect( - result, - equals(>[ - ['abc'] - ])); + result, + equals(>[ + ['abc'], + ]), + ); - isolates.stop(); + await isolates.stop(); }); test('Test `workerFunction`', () { @@ -230,13 +231,18 @@ void _addWorkerMappings() { IsolateManager.addWorkerMapping(add, 'add'); IsolateManager.addWorkerMapping(addFuture, 'addFuture'); IsolateManager.addWorkerMapping( - isolateCallbackSimpleFunctionWithSpecifiedType, - 'isolateCallbackSimpleFunctionWithSpecifiedType'); + isolateCallbackSimpleFunctionWithSpecifiedType, + 'isolateCallbackSimpleFunctionWithSpecifiedType', + ); IsolateManager.addWorkerMapping( - isolateCallbackSimpleFunction, 'isolateCallbackSimpleFunction'); + isolateCallbackSimpleFunction, + 'isolateCallbackSimpleFunction', + ); IsolateManager.addWorkerMapping(a2DTo1DList, 'a2DTo1DList'); IsolateManager.addWorkerMapping( - isolateCallbackFunction, 'isolateCallbackFunction'); + isolateCallbackFunction, + 'isolateCallbackFunction', + ); IsolateManager.addWorkerMapping(aDynamicMap, 'aDynamicMap'); IsolateManager.addWorkerMapping(a1DTo2DList, 'a1DTo2DList'); } diff --git a/test/isolate_manager_test.dart b/test/isolate_manager_test.dart index cca5c8c..0756ff0 100644 --- a/test/isolate_manager_test.dart +++ b/test/isolate_manager_test.dart @@ -44,7 +44,7 @@ void main() { expect(result, fibonacci(3)); - isolateManager.stop(); + await isolateManager.stop(); }); test('Test IsolateManager.create', () async { @@ -67,10 +67,10 @@ void main() { for (int i = 0; i < 10; i++) isolateManager.compute(i).then((value) { expect(value, fibonacci(i)); - }) + }), ]); - isolateManager.stop(); + await isolateManager.stop(); }); test('Test IsolateManager.createCustom', () async { @@ -79,7 +79,8 @@ void main() { isolateFunction, concurrent: 4, initialParams: ['Test initialParams 0', 'Test initialParams 1'], - )..start(); + ); + await isolateManager.start(); isolateManager.stream .listen((value) {}) @@ -90,7 +91,7 @@ void main() { for (int i = 0; i < 10; i++) isolateManager.compute(i).then((value) { expect(value, fibonacci(i)); - }) + }), ]); await isolateManager.restart(); @@ -99,7 +100,7 @@ void main() { for (int i = 5; i < 13; i++) isolateManager.compute(i).then((value) { expect(value, fibonacci(i)); - }) + }), ]); await expectLater(() => isolateManager.sendMessage(-1), throwsStateError); @@ -111,7 +112,8 @@ void main() { final isolateManager = IsolateManager.createCustom( isolateFunction, concurrent: 1, - )..start(); + ); + await isolateManager.start(); await expectLater(() => isolateManager(-1), throwsStateError); await isolateManager.stop(); @@ -124,7 +126,8 @@ void main() { isolateFunctionWithAutomaticallyHandlers, concurrent: 4, initialParams: ['Test initialParams 0', 'Test initialParams 1'], - )..start(); + ); + await isolateManager.start(); isolateManager.stream .listen((value) {}) @@ -135,7 +138,7 @@ void main() { for (int i = 0; i < 10; i++) isolateManager.compute(i).then((value) { expect(value, fibonacci(i)); - }) + }), ]); await isolateManager.restart(); @@ -144,7 +147,7 @@ void main() { for (int i = 5; i < 13; i++) isolateManager.compute(i).then((value) { expect(value, fibonacci(i)); - }) + }), ]); await expectLater(() => isolateManager.sendMessage(-1), throwsStateError); @@ -166,7 +169,7 @@ void main() { final realFib = fibonacci(i); expect(value, realFib); - }) + }), ]); await isolateManager.stop(); @@ -208,9 +211,7 @@ void main() { await isolateManager.start(); await expectLater( - () => isolateManager.compute([50, 50], callback: (value) { - return true; - }), + () => isolateManager.compute([50, 50], callback: (value) => true), throwsStateError, ); await isolateManager.stop(); @@ -222,14 +223,14 @@ void main() { concurrent: 2, ); await isolateManager.start(); - final List futures = []; + final List> futures = []; for (var i = 0; i < 100; i++) { futures.add(isolateManager.compute([i, 20])); } await expectLater( - () async => await Future.wait(futures, eagerError: true), + () async => Future.wait(futures, eagerError: true), throwsStateError, ); await isolateManager.stop(); @@ -243,7 +244,7 @@ void main() { concurrent: 2, ); await isolateManager.start(); - final List futures = []; + final List> futures = []; for (var i = 0; i < 100; i++) { futures.add(isolateManager.compute([i, 20], callback: (value) => true)); @@ -262,7 +263,7 @@ void main() { concurrent: 2, ); await isolateManager.start(); - final List futures = []; + final List> futures = []; for (var i = 0; i < 100; i++) { futures.add(isolateManager.compute([i, 20])); @@ -283,7 +284,7 @@ void main() { concurrent: 2, ); await isolateManager.start(); - final List futures = []; + final List> futures = []; for (var i = 0; i < 100; i++) { futures.add(isolateManager.compute([i, 20], callback: (value) => true)); @@ -304,16 +305,19 @@ void main() { ); await isolateManager.start(); - final result = await isolateManager.compute(1, callback: (value) { - final decoded = jsonDecode(value) as Map; - // Do not return this [value] as the final result - if (decoded.containsKey('source')) { - return false; - } + final result = await isolateManager.compute( + 1, + callback: (value) { + final decoded = jsonDecode(value) as Map; + // Do not return this [value] as the final result + if (decoded.containsKey('source')) { + return false; + } - // Return this [value] as the final result - return true; - }); + // Return this [value] as the final result + return true; + }, + ); final decoded = jsonDecode(result) as Map; expect( @@ -332,16 +336,19 @@ void main() { ); await isolateManager.start(); - final result = await isolateManager.compute(1, callback: (value) { - final decoded = jsonDecode(value) as Map; - // Do not return this [value] as the final result - if (decoded.containsKey('source')) { - return false; - } + final result = await isolateManager.compute( + 1, + callback: (value) { + final decoded = jsonDecode(value) as Map; + // Do not return this [value] as the final result + if (decoded.containsKey('source')) { + return false; + } - // Return this [value] as the final result - return true; - }); + // Return this [value] as the final result + return true; + }, + ); final decoded = jsonDecode(result) as Map; expect( @@ -360,16 +367,19 @@ void main() { ); await isolateManager.start(); - final result = await isolateManager.compute(1, callback: (value) { - final decoded = jsonDecode(value) as Map; - // Do not return this [value] as the final result - if (decoded.containsKey('source')) { - return false; - } + final result = await isolateManager.compute( + 1, + callback: (value) { + final decoded = jsonDecode(value) as Map; + // Do not return this [value] as the final result + if (decoded.containsKey('source')) { + return false; + } - // Return this [value] as the final result - return true; - }); + // Return this [value] as the final result + return true; + }, + ); final decoded = jsonDecode(result) as Map; expect( @@ -389,16 +399,19 @@ void main() { ); await isolateManager.start(); - final result = await isolateManager.compute(1, callback: (value) { - final decoded = jsonDecode(value) as Map; - // Do not return this [value] as the final result - if (decoded.containsKey('source')) { - return false; - } + final result = await isolateManager.compute( + 1, + callback: (value) { + final decoded = jsonDecode(value) as Map; + // Do not return this [value] as the final result + if (decoded.containsKey('source')) { + return false; + } - // Return this [value] as the final result - return true; - }); + // Return this [value] as the final result + return true; + }, + ); final decoded = jsonDecode(result) as Map; expect( @@ -443,7 +456,7 @@ void main() { final list = [ ['a', 'b', 'v'], - ['d', 'e', 'f'] + ['d', 'e', 'f'], ]; final result = await isolate.compute(list); @@ -470,7 +483,7 @@ void main() { } expect(queueStrategies.queuesCount, equals(10)); expect(queueStrategies.continueIfMaxCountExceeded(), true); - List result = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + final result = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; while (queueStrategies.hasNext()) { expect(queueStrategies.getNext().params, equals(result.removeAt(0))); } @@ -496,7 +509,7 @@ void main() { queueStrategies.add(IsolateQueue(i, null)); } expect(queueStrategies.queuesCount, equals(3)); - List result = [0, 1, 9]; + final result = [0, 1, 9]; while (queueStrategies.hasNext()) { expect(queueStrategies.getNext().params, equals(result.removeAt(0))); } @@ -509,7 +522,7 @@ void main() { queueStrategies.add(IsolateQueue(i, null), addToTop: true); } expect(queueStrategies.queuesCount, equals(3)); - List result = [9, 8, 7]; + final result = [9, 8, 7]; while (queueStrategies.hasNext()) { expect(queueStrategies.getNext().params, equals(result.removeAt(0))); } @@ -522,7 +535,7 @@ void main() { queueStrategies.add(IsolateQueue(i, null)); } expect(queueStrategies.queuesCount, equals(3)); - List result = [7, 8, 9]; + final result = [7, 8, 9]; while (queueStrategies.hasNext()) { expect(queueStrategies.getNext().params, equals(result.removeAt(0))); } @@ -535,7 +548,7 @@ void main() { queueStrategies.add(IsolateQueue(i, null), addToTop: true); } expect(queueStrategies.queuesCount, equals(3)); - List result = [9, 1, 0]; + final result = [9, 1, 0]; while (queueStrategies.hasNext()) { expect(queueStrategies.getNext().params, equals(result.removeAt(0))); } @@ -549,7 +562,7 @@ void main() { queueStrategies.add(IsolateQueue(i, null)); } expect(queueStrategies.queuesCount, equals(3)); - List result = [0, 1, 2]; + final result = [0, 1, 2]; while (queueStrategies.hasNext()) { expect(queueStrategies.getNext().params, equals(result.removeAt(0))); } @@ -563,7 +576,7 @@ void main() { queueStrategies.add(IsolateQueue(i, null), addToTop: true); } expect(queueStrategies.queuesCount, equals(3)); - List result = [2, 1, 0]; + final result = [2, 1, 0]; while (queueStrategies.hasNext()) { expect(queueStrategies.getNext().params, equals(result.removeAt(0))); } @@ -719,7 +732,7 @@ int errorFunction(List value) { @pragma('vm:entry-point') Future errorFunctionFuture(List value) async { - await Future.delayed(Duration(seconds: 1)); + await Future.delayed(const Duration(seconds: 1)); if (value[0] == 50) { return throw StateError('The exception is threw at value[0] = ${value[0]}'); @@ -729,18 +742,23 @@ Future errorFunctionFuture(List value) async { void _addWorkerMappings() { IsolateManager.addWorkerMapping( - isolateCallbackSimpleFunctionWithSpecifiedType, - 'isolateCallbackSimpleFunctionWithSpecifiedType'); + isolateCallbackSimpleFunctionWithSpecifiedType, + 'isolateCallbackSimpleFunctionWithSpecifiedType', + ); IsolateManager.addWorkerMapping(fibonacci, 'fibonacci'); IsolateManager.addWorkerMapping(addException, 'addException'); IsolateManager.addWorkerMapping(add, 'add'); IsolateManager.addWorkerMapping(addFuture, 'addFuture'); IsolateManager.addWorkerMapping(fibonacciRecursive, 'fibonacciRecursive'); IsolateManager.addWorkerMapping( - isolateCallbackFunction, 'isolateCallbackFunction'); + isolateCallbackFunction, + 'isolateCallbackFunction', + ); IsolateManager.addWorkerMapping(a2DTo1DList, 'a2DTo1DList'); IsolateManager.addWorkerMapping( - isolateCallbackSimpleFunction, 'isolateCallbackSimpleFunction'); + isolateCallbackSimpleFunction, + 'isolateCallbackSimpleFunction', + ); IsolateManager.addWorkerMapping(a1DTo2DList, 'a1DTo2DList'); IsolateManager.addWorkerMapping(aStringList, 'aStringList'); IsolateManager.addWorkerMapping(aDynamicMap, 'aDynamicMap');