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 | | 12 | void _onError(ex, st) => _controller.addError(SquadronException.from(ex, st)); |
51 | | |
|
52 | | 2 | @override |
53 | | | void cancel([String? message]) { |
54 | | 2 | super.cancel(message); |
55 | | 4 | if (!_worker.isCompleted) { |
56 | | | // task canceled before it got scheduled |
57 | | 4 | _worker.complete(null); |
58 | | | } |
59 | | 4 | if (_controller.subscription != null) { |
60 | | | // task canceled after a listener subscribed to the stream |
61 | | 2 | _closeWithError(canceledException!); |
62 | | | } |
63 | | | } |
64 | | |
|
65 | | 4 | @override |
66 | | | Future<bool> execute(W worker) { |
67 | | 4 | if (canceledException == null) { |
68 | | | // run with worker |
69 | | 8 | _worker.complete(worker); |
70 | | | } |
71 | | 8 | return _controller.done |
72 | | 12 | .then((_) => canceledException == null) |
73 | | 4 | .catchError((_) => false); |
74 | | | } |
75 | | | } |