UNPKG

@fimbul-works/observable

Version:

A lightweight, strongly-typed TypeScript library for reactive programming patterns, providing observable collections, values, and event handling.

76 lines (75 loc) 3.05 kB
import type { ErrorHandler, EventHandler } from "./types"; /** * Signal class implements a publish/subscribe pattern for event handling with error management * and support for both synchronous and asynchronous operations. * * @template T The type of signal to emit * @template R The return type of handlers (void or Promise<void>) */ export declare class Signal<T, R = void | Promise<void>> { #private; /** * Registers a callback function to be executed when the signal is emitted. * The callback can be synchronous or asynchronous (return a Promise). * * @param fn - Function to be called when the signal is emitted * @returns A cleanup function that removes the handler when called */ connect(fn: EventHandler<T, R>): () => void; /** * Registers a one-time callback function that will be automatically removed after being called. * The callback can be synchronous or asynchronous (return a Promise). * * @param fn - Function to be called once when the signal is emitted * @returns A cleanup function that removes the handler when called */ once(fn: EventHandler<T, R>): () => void; /** * Removes a previously registered callback function. * @param fn - The callback function to remove. A falsy value will disconnect all subscribers. * @returns this for method chaining */ disconnect(fn?: EventHandler<T, R>): this; /** * Triggers the signal, executing all registered callbacks with the provided data. * This method runs synchronously and doesn't wait for any promises returned by handlers. * * @param data - The data to pass to the callback functions * @returns The number of handlers that were called */ emit(data: T): number; /** * Triggers the signal and waits for all handlers to complete, including any that return Promises. * * @param data - The data to pass to the callback functions * @returns Promise resolving to the number of handlers that were called */ emitAsync(data: T): Promise<number>; /** * Registers an error handler function. * @param fn - The error handler function to add * @returns A cleanup function that removes the error handler when called */ connectError(fn: ErrorHandler): () => void; /** * Removes a previously registered error handler function. * @param fn - The error handler function to remove * @returns this for method chaining */ disconnectError(fn: ErrorHandler): this; /** * Returns the total number of handlers currently registered. * @returns The number of all types of handlers combined */ listenerCount(): number; /** * Checks if there are any handlers registered. * @returns True if there are any handlers, false otherwise */ hasHandlers(): boolean; /** * Cleans up all event subscriptions and releases resources. * Call this method when the signal is no longer needed. */ destroy(): void; }