| b69ab31 | | | 1 | /** |
| b69ab31 | | | 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| b69ab31 | | | 3 | * |
| b69ab31 | | | 4 | * This source code is licensed under the MIT license found in the |
| b69ab31 | | | 5 | * LICENSE file in the root directory of this source tree. |
| b69ab31 | | | 6 | */ |
| b69ab31 | | | 7 | |
| b69ab31 | | | 8 | /** |
| b69ab31 | | | 9 | * A token which represents some ongoing work which may be cancelled. |
| b69ab31 | | | 10 | * Typically created by the caller of some async work, |
| b69ab31 | | | 11 | * and used by the caller to cancel and used by the |
| b69ab31 | | | 12 | * implementation to observe and respond to cancellations. |
| b69ab31 | | | 13 | * This is similar to CancellationToken used in VS Code. |
| b69ab31 | | | 14 | * |
| b69ab31 | | | 15 | * Tokens should only be cancelled once. |
| b69ab31 | | | 16 | * |
| b69ab31 | | | 17 | * Token can be polled with isCancelled, |
| b69ab31 | | | 18 | * or you can subscribe with onCancel. |
| b69ab31 | | | 19 | */ |
| b69ab31 | | | 20 | export class CancellationToken { |
| b69ab31 | | | 21 | public isCancelled = false; |
| b69ab31 | | | 22 | |
| b69ab31 | | | 23 | private callbacks: Array<() => unknown> = []; |
| b69ab31 | | | 24 | public onCancel(cb: () => unknown) { |
| b69ab31 | | | 25 | if (this.isCancelled) { |
| b69ab31 | | | 26 | cb(); |
| b69ab31 | | | 27 | return () => undefined; |
| b69ab31 | | | 28 | } |
| b69ab31 | | | 29 | this.callbacks.push(cb); |
| b69ab31 | | | 30 | return () => { |
| b69ab31 | | | 31 | const position = this.callbacks.indexOf(cb); |
| b69ab31 | | | 32 | if (position !== -1) { |
| b69ab31 | | | 33 | this.callbacks.splice(position, 1); |
| b69ab31 | | | 34 | } |
| b69ab31 | | | 35 | }; |
| b69ab31 | | | 36 | } |
| b69ab31 | | | 37 | |
| b69ab31 | | | 38 | public cancel() { |
| b69ab31 | | | 39 | if (!this.isCancelled) { |
| b69ab31 | | | 40 | this.isCancelled = true; |
| b69ab31 | | | 41 | this.callbacks.forEach(c => c()); |
| b69ab31 | | | 42 | } |
| b69ab31 | | | 43 | } |
| b69ab31 | | | 44 | } |