From a84351ad0c20ad001a4a8ec41e0641b6b4424671 Mon Sep 17 00:00:00 2001 From: Daniel Imms <2193314+Tyriar@users.noreply.github.com> Date: Fri, 18 Aug 2023 14:15:56 -0700 Subject: [PATCH] Add MutableDisposable Part of #4685 --- src/common/Lifecycle.ts | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/common/Lifecycle.ts b/src/common/Lifecycle.ts index b3a7cc21..659403de 100644 --- a/src/common/Lifecycle.ts +++ b/src/common/Lifecycle.ts @@ -50,6 +50,42 @@ export abstract class Disposable implements IDisposable { } } +export class MutableDisposable implements IDisposable { + private _value?: T; + private _isDisposed = false; + + /** + * Gets the value if it exists. + */ + public get value(): T | undefined { + return this._isDisposed ? undefined : this._value; + } + + /** + * Sets the value, disposing of the old value if it exists. + */ + public set value(value: T | undefined) { + if (this._isDisposed || value === this._value) { + return; + } + this._value?.dispose(); + this._value = value; + } + + /** + * Resets the stored value and disposes of the previously stored value. + */ + public clear(): void { + this.value = undefined; + } + + public dispose(): void { + this._isDisposed = true; + this._value?.dispose(); + this._value = undefined; + } +} + /** * Wrap a function in a disposable. */