tuil
ReferencePackages@mwillbanks/tuil-coreAPI

DisposableStack

class exported by @mwillbanks/tuil-core.

View rawEdit

class

Public class exported by @mwillbanks/tuil-core.

export class DisposableStack implements Disposable {
  readonly #resources: Disposable[];
  #disposed: boolean;

  constructor() {
    this.#resources = [];
    this.#disposed = false;
  }

  get disposed(): boolean {
    return this.#disposed;
  }

  use<T extends Disposable>(value: T): T {
    if (this.#disposed) {
      throw new Error("Cannot add a resource to a disposed stack");
    }
    this.#resources.push(value);
    return value;
  }

  defer(dispose: Disposer): void {
    if (this.#disposed) {
      throw new Error("Cannot add a resource to a disposed stack");
    }
    this.#resources.push(toDisposable(dispose));
  }

  async dispose(): Promise<void> {
    if (this.#disposed) {
      return;
    }
    this.#disposed = true;
    const errors: unknown[] = [];
    for (const resource of this.#resources.reverse()) {
      try {
        await resource.dispose();
      } catch (error) {
        errors.push(error);
      }
    }
    this.#resources.length = 0;
    if (errors.length > 0) {
      throw new AggregateError(
        errors,
        "One or more resources failed to dispose",
      );
    }
  }
}

Members

MemberTypeRequiredDescriptionRelated types
#resourcesDisposable[]YesThe #resources member uses the Disposable[] contract.Disposable
#disposedbooleanYesThe #disposed member uses the boolean contract.
__constructoranyYesThe __constructor member uses the any contract.
disposedbooleanYesThe disposed member uses the boolean contract.
use<T extends Disposable>(value: T) => TYesThe use member uses the <T extends Disposable>(value: T) => T contract.Disposable
defer(dispose: Disposer) => voidYesThe defer member uses the (dispose: Disposer) => void contract.Disposer
dispose() => Promise<void>YesThe dispose member uses the () => Promise<void> contract.

Parameters

This declaration has no public members.

Returns

This declaration does not return a value.

Throws

No thrown errors are documented for this declaration.

Source

View the secondary source reference

Package

@mwillbanks/tuil-core

On this page