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 | | 12 | WorkerStreamTask(this._producer, PerfCounter? counter) : super(counter) { |
14 | | 16 | _controller = ForwardStreamController<T>(onListen: () async { |
15 | | 4 | try { |
16 | | 8 | throwIfCanceled(); |
17 | | 8 | if (_controller.isClosed) return; |
18 | | 12 | final stream = await _streamer.future; |
19 | | 8 | if (_controller.isClosed) { |
20 | | | // we might have a problem here: the controller is closed but the worker |
21 | | | // has started streaming; cancel the operation |
22 | | 0 | stream.listen((_) {}).cancel(); |
23 | | | } else { |
24 | | 16 | _controller.attachSubscription(stream.listen( |
25 | | 8 | _onData, |
26 | | 8 | onError: _onError, |
27 | | 12 | onDone: _controller.close, |
28 | | | cancelOnError: false, |
29 | | | )); |
30 | | | } |
31 | | 0 | } catch (ex, st) { |
32 | | 0 | _closeWithError(SquadronException.from(ex, st)); |
33 | | | } |
34 | | 4 | }); |
35 | | 4 | } |
36 | | |
|
37 | | | final Stream<T> Function(W worker) _producer; |
38 | | | final _streamer = Completer<Stream<T>>(); |
39 | | |
|
40 | | 5 | late final ForwardStreamController<T> _controller; |
41 | | |
|
42 | | 4 | @override |
43 | | 8 | Stream<T> get stream => _controller.stream; |
44 | | |
|
45 | | 1 | void _closeWithError(SquadronException ex) { |
46 | | 2 | _controller.addError(ex); |
47 | | 3 | _controller.close(); |
48 | | | } |
49 | | |
|
50 | | 17 | void _onData(T data) => _controller.add(data); |
51 | | |
|
52 | | 16 | void _onError(ex, st) => _controller.addError(SquadronException.from(ex, st)); |
53 | | |
|
54 | | 1 | @override |
55 | | 1 | void cancel([String? message]) { |
56 | | 2 | super.cancel(message); |
57 | | 3 | _closeWithError(canceledException!); |
58 | | 1 | } |
59 | | |
|
60 | | 4 | @override |
61 | | 4 | Future<bool> execute(W worker) { |
62 | | 4 | try { |
63 | | 4 | throwIfCanceled(); |
64 | | 12 | final stream = _producer(worker); |
65 | | 12 | _streamer.complete(stream); |
66 | | 20 | return _controller.done.then((_) => true); |
67 | | 0 | } catch (ex, st) { |
68 | | 0 | _closeWithError(SquadronException.from(ex, st)); |
69 | | 0 | return Future.value(false); |
70 | | | } |
71 | | 4 | } |
72 | | | } |