| 1 | | | import 'dart:async'; |
| 2 | | | |
| 3 | | | import '../_impl/xplat/_forward_stream_controller.dart'; |
| 4 | | | import '../exceptions/squadron_exception.dart'; |
| 5 | | | import '../stats/perf_counter.dart'; |
| 6 | | | import '../worker/worker.dart'; |
| 7 | | | import '_worker_task.dart'; |
| 8 | | | import 'stream_task.dart'; |
| 9 | | | |
| 10 | | | final class WorkerStreamTask<T, W extends Worker> extends WorkerTask<T, W> |
| 11 | | | implements StreamTask<T> { |
| 12 | | | /// Creates a new [StreamTask]. |
| 13 | | 8 | WorkerStreamTask(this._producer, PerfCounter? counter) : super(counter) { |
| 14 | | 12 | _controller = ForwardStreamController<T>(onListen: () async { |
| 15 | | | try { |
| 16 | | 8 | final worker = await _worker.future; |
| 17 | | 4 | if (canceledException != null || worker == null) { |
| 18 | | | // the task was canceled |
| 19 | | 2 | throw canceledException!; |
| 20 | | | } else { |
| 21 | | | // otherwise, forward data from the worker |
| 22 | | 20 | _controller.attachSubscription(_producer(worker).listen( |
| 23 | | 4 | _onData, |
| 24 | | 4 | onError: _onError, |
| 25 | | 8 | onDone: _controller.close, |
| 26 | | | cancelOnError: false, |
| 27 | | | )); |
| 28 | | | } |
| 29 | | | } catch (ex, st) { |
| 30 | | 4 | _closeWithError(SquadronException.from(ex, st)); |
| 31 | | | } |
| 32 | | | }); |
| 33 | | | } |
| 34 | | | |
| 35 | | | final Stream<T> Function(W worker) _producer; |
| 36 | | | final _worker = Completer<W?>(); |
| 37 | | | |
| 38 | | | late final ForwardStreamController<T> _controller; |
| 39 | | | |
| 40 | | 4 | @override |
| 41 | | 8 | Stream<T> get stream => _controller.stream; |
| 42 | | | |
| 43 | | 2 | void _closeWithError(SquadronException ex) { |
| 44 | | 4 | _controller.addError(ex); |
| 45 | | 4 | _controller.close(); |
| 46 | | | } |
| 47 | | | |
| 48 | | 12 | void _onData(T data) => _controller.add(data); |
| 49 | | | |
| 50 | | 3 | void _onError(Object ex, [StackTrace? st]) => |
| 51 | | 9 | _controller.addError(SquadronException.from(ex, st)); |
| 52 | | | |
| 53 | | 2 | @override |
| 54 | | | void cancel([String? message]) { |
| 55 | | 2 | super.cancel(message); |
| 56 | | 4 | if (!_worker.isCompleted) { |
| 57 | | | // task canceled before it got scheduled |
| 58 | | 4 | _worker.complete(null); |
| 59 | | | } |
| 60 | | 4 | if (_controller.subscription != null) { |
| 61 | | | // task canceled after a listener subscribed to the stream |
| 62 | | 2 | _closeWithError(canceledException!); |
| 63 | | | } |
| 64 | | | } |
| 65 | | | |
| 66 | | 4 | @override |
| 67 | | | Future<bool> execute(W worker) { |
| 68 | | 4 | if (canceledException == null) { |
| 69 | | | // run with worker |
| 70 | | 8 | _worker.complete(worker); |
| 71 | | | } |
| 72 | | 8 | return _controller.done |
| 73 | | 12 | .then((_) => canceledException == null) |
| 74 | | 4 | .catchError((_) => false); |
| 75 | | | } |
| 76 | | | } |