Skip to content

Instantly share code, notes, and snippets.

@colelawrence
Created December 19, 2023 20:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colelawrence/f055349c7192d5444a57e8aa18a49d11 to your computer and use it in GitHub Desktop.
Save colelawrence/f055349c7192d5444a57e8aa18a49d11 to your computer and use it in GitHub Desktop.
Dispose Pool (Subscription) class
export interface IDisposable {
dispose(): void;
}
export class DisposePool implements IDisposable {
#fns: null | (() => void)[] = [];
#pool: null | IDisposable[] = [];
get disposed() {
return this.#pool === null;
}
dispose() {
if (this.#pool == null) return;
const pool = this.#pool;
this.#pool = null;
const fns = this.#fns!;
this.#fns = null;
for (let i = 0; i < pool.length; i++) {
pool[i].dispose();
}
for (let i = 0; i < fns.length; i++) {
fns[i]();
}
}
addfn(fn: () => void) {
if (this.#fns) {
this.#fns.push(fn);
} else {
fn();
}
}
add<T extends IDisposable>(value: T): T {
if (this.#pool) {
this.#pool.push(value);
} else {
value.dispose();
}
return value;
}
}
export function isDisposable(value: any): value is IDisposable {
return value && typeof value.dispose === "function";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment