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. */