1 | | | import 'dart:async'; |
2 | | |
|
3 | | | import '../exceptions/squadron_exception.dart'; |
4 | | | import '../stats/perf_counter.dart'; |
5 | | | import '../worker/worker.dart'; |
6 | | | import '_worker_task.dart'; |
7 | | | import 'value_task.dart'; |
8 | | |
|
9 | | | final class WorkerValueTask<T, W extends Worker> extends WorkerTask<T, W> |
10 | | | implements ValueTask<T> { |
11 | | | /// Creates a new [ValueTask]. |
12 | | 9 | WorkerValueTask(this._computer, PerfCounter? counter) : super(counter); |
13 | | |
|
14 | | | final Future<T> Function(W worker) _computer; |
15 | | | final _result = Completer<T>(); |
16 | | |
|
17 | | 3 | @override |
18 | | 9 | Future<T> get value => _result.future; |
19 | | |
|
20 | | 4 | void _failure(SquadronException exception) { |
21 | | 6 | if (!_result.isCompleted) { |
22 | | 6 | _result.completeError(exception); |
23 | | | } |
24 | | 2 | } |
25 | | |
|
26 | | 3 | void _success(dynamic data) { |
27 | | 9 | if (!_result.isCompleted) { |
28 | | 9 | _result.complete(data); |
29 | | | } |
30 | | | } |
31 | | |
|
32 | | 2 | @override |
33 | | 2 | void cancel([String? message]) { |
34 | | 4 | super.cancel(message); |
35 | | 6 | _failure(canceledException!); |
36 | | 2 | } |
37 | | |
|
38 | | 3 | @override |
39 | | 3 | Future<bool> execute(W worker) async { |
40 | | 3 | try { |
41 | | 3 | throwIfCanceled(); |
42 | | 9 | final res = await _computer(worker); |
43 | | 3 | _success(res); |
44 | | 3 | return true; |
45 | | 1 | } catch (ex, st) { |
46 | | 3 | _failure(SquadronException.from(ex, st)); |
47 | | 1 | return false; |
48 | | | } |
49 | | 3 | } |
50 | | | } |