1 | | | import 'squadron_error.dart'; |
2 | | | import 'worker_exception.dart'; |
3 | | | import 'worker_request.dart'; |
4 | | | import 'worker_service.dart' show SquadronCallback; |
5 | | |
|
6 | | | /// Cancellation token used in platform workers. These tokens are not designed to be cancelled or listened to by |
7 | | | /// holders. Instead, worker services receiving a [CancellationToken] should verify the token's [cancelled] status |
8 | | | /// and stop processing if the flag is set to [true]. |
9 | | | class CancellationToken { |
10 | | 1 | CancellationToken(this.id, [String? message]) : _message = message; |
11 | | |
|
12 | | | static const _$token = 'a'; |
13 | | | static const _$message = 'b'; |
14 | | |
|
15 | | | /// Deseralization of a [CancellationToken] |
16 | | 1 | static CancellationToken? deserialize(Map? token) => (token == null) |
17 | | | ? null |
18 | | 3 | : CancellationToken(token[_$token], token[_$message]); |
19 | | |
|
20 | | | /// The token's id |
21 | | | final int id; |
22 | | |
|
23 | | | /// Flag indicating whether the token was cancelled or not. |
24 | | 3 | bool get cancelled => exception != null; |
25 | | |
|
26 | | | /// Exception to be thrown upon cancellation |
27 | | 0 | CancelledException? get exception => null; |
28 | | |
|
29 | | | /// Message associated with the token. |
30 | | 3 | String? get message => _message; |
31 | | | final String? _message; |
32 | | |
|
33 | | | /// Seralization of a [CancellationToken] |
34 | | 5 | Map serialize() => {_$token: id, _$message: _message}; |
35 | | |
|
36 | | | /// Called just before processing a [WorkerRequest], but should only be implemented by cancellation tokens that |
37 | | | /// need to cancel automatically. |
38 | | 2 | void start() {} |
39 | | |
|
40 | | | /// Registers a listener that will be notified when the token is cancelled. Because a [CancellationToken] is not |
41 | | | /// designed to be listened to, it always throws a [SquadronError]. |
42 | | 0 | void addListener(SquadronCallback listener) => |
43 | | 0 | throw newSquadronError('CancellationToken may not be listened to'); |
44 | | |
|
45 | | | /// Unregisters a listener that has been installed with [addListener]. |
46 | | 0 | void removeListener(SquadronCallback listener) {} |
47 | | | } |