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