1 | | | import 'cancellation_token.dart'; |
2 | | | import '_sequence_id.dart'; |
3 | | | import 'squadron.dart'; |
4 | | | import 'worker_exception.dart'; |
5 | | | import 'worker_service.dart' show SquadronCallback; |
6 | | |
|
7 | | 2 | void _safeInvoke(SquadronCallback? callback) { |
8 | | 1 | try { |
9 | | 1 | if (callback != null) { |
10 | | 2 | callback(); |
11 | | | } |
12 | | | } catch (e) { |
13 | | 0 | Squadron.warning('notification to listener $callback failed: $e'); |
14 | | | } |
15 | | 1 | } |
16 | | |
|
17 | | | /// Base class for cancellation tokens used by callers of worker services. It implements the logic to register, |
18 | | | /// notify and unregister token listeners. This cancellation token can be cancelled programmatically by calling |
19 | | | /// [cancel]. |
20 | | | class CancellableToken extends CancellationToken { |
21 | | 1 | CancellableToken([String? message]) |
22 | | 4 | : super(SequenceId.instance.next(), message); |
23 | | |
|
24 | | 1 | @override |
25 | | 2 | CancelledException? get exception => _exception; |
26 | | | CancelledException? _exception; |
27 | | |
|
28 | | 2 | void setException(CancelledException exception) { |
29 | | 2 | _exception ??= exception; |
30 | | 4 | _listeners?.toList().forEach(_safeInvoke); |
31 | | 1 | } |
32 | | |
|
33 | | | /// Cancels the token and notifies listeners. |
34 | | 2 | void cancel() => |
35 | | 5 | setException(_exception ?? CancelledException(message: message)); |
36 | | |
|
37 | | 1 | List<SquadronCallback>? _listeners; |
38 | | |
|
39 | | | /// Registers a listener that will be notified when the token is cancelled. |
40 | | 1 | @override |
41 | | 1 | void addListener(SquadronCallback listener) => |
42 | | 5 | _listeners = (_listeners ?? <SquadronCallback>[])..add(listener); |
43 | | |
|
44 | | 1 | @override |
45 | | 1 | void removeListener(SquadronCallback listener) => |
46 | | 3 | _listeners?.remove(listener); |
47 | | | } |