addons/shared/CancellationToken.tsblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318/**
b69ab319 * A token which represents some ongoing work which may be cancelled.
b69ab3110 * Typically created by the caller of some async work,
b69ab3111 * and used by the caller to cancel and used by the
b69ab3112 * implementation to observe and respond to cancellations.
b69ab3113 * This is similar to CancellationToken used in VS Code.
b69ab3114 *
b69ab3115 * Tokens should only be cancelled once.
b69ab3116 *
b69ab3117 * Token can be polled with isCancelled,
b69ab3118 * or you can subscribe with onCancel.
b69ab3119 */
b69ab3120export class CancellationToken {
b69ab3121 public isCancelled = false;
b69ab3122
b69ab3123 private callbacks: Array<() => unknown> = [];
b69ab3124 public onCancel(cb: () => unknown) {
b69ab3125 if (this.isCancelled) {
b69ab3126 cb();
b69ab3127 return () => undefined;
b69ab3128 }
b69ab3129 this.callbacks.push(cb);
b69ab3130 return () => {
b69ab3131 const position = this.callbacks.indexOf(cb);
b69ab3132 if (position !== -1) {
b69ab3133 this.callbacks.splice(position, 1);
b69ab3134 }
b69ab3135 };
b69ab3136 }
b69ab3137
b69ab3138 public cancel() {
b69ab3139 if (!this.isCancelled) {
b69ab3140 this.isCancelled = true;
b69ab3141 this.callbacks.forEach(c => c());
b69ab3142 }
b69ab3143 }
b69ab3144}