Created
December 19, 2023 20:53
-
-
Save colelawrence/f055349c7192d5444a57e8aa18a49d11 to your computer and use it in GitHub Desktop.
Dispose Pool (Subscription) class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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