API reference@evolu/commonFunction › disposable

Call Signature

function disposable<T>(
  value: T extends Disposable ? Omit<T, typeof dispose> : T,
  disposer?: DisposableStack,
): T extends Disposable ? T : T & Disposable;

Defined in: packages/common/src/Function.ts:161

Creates an object that follows JavaScript disposal semantics.

The first argument is the object to make disposable. The returned object gets a disposal method and its functions are wrapped with a disposal guard. This is the JavaScript equivalent of .NET ObjectDisposedException: once an object has been disposed, calling its methods is a programmer error and should throw immediately instead of continuing with invalid state. Evolu asserts this invariant with the "Cannot use a disposed object." message.

The second argument is an optional disposer. When provided, it is moved into the returned object, and the returned object's disposal method disposes it. Omit it when the object has no cleanup resources but still must become unusable after disposal, such as with reference count helpers where disposal enforces correct ownership tracking.

Example

import { disposable } from "@evolu/common";

let cleaned = false;
const createResource = () => {
  using disposer = new DisposableStack();
  disposer.defer(() => {
    cleaned = true;
  });
  return disposable({ read: () => "ready" }, disposer);
};

const resource = createResource();
expect(resource.read()).toBe("ready");
resource[Symbol.dispose]();

expect(cleaned).toBe(true);
expect(() => resource.read()).toThrow("Cannot use a disposed object.");

Call Signature

function disposable<T>(
  value: T extends AsyncDisposable ? Omit<T, typeof asyncDispose> : T,
  disposer: AsyncDisposableStack,
): T extends AsyncDisposable ? T : T & AsyncDisposable;

Defined in: packages/common/src/Function.ts:167

Creates an asynchronously disposable object.