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) 2.88 kB
import type { Observable } from "./types.js"; /** * Represents a value that can be observed for changes. * Notifies observers whenever the value is updated. * * @template T The type of value being stored and observed * @implements {Observable<T>} */ export declare class ObservableValue<T> implements Observable<T> { #private; /** * Creates a new ObservableValue instance. * @param initial - The initial value to store */ constructor(initial: T); /** * Retrieves the current value. * @returns {T} The current stored value */ get(): T; /** * Updates the stored value and notifies observers. * @param newValue - The new value to store * @returns {this} */ set(newValue: T): this; /** * Updates the stored value and waits for all observer callbacks to complete. * @param newValue - The new value to store * @returns {Promise<this>} */ setAsync(newValue: T): Promise<this>; /** * Updates the value using a transformation function and notifies observers. * The update is atomic - observers will only be notified once with the final value. * @param updateFn - Function that receives the current value and returns the new value * @returns {this} */ update(updateFn: (current: T) => T): this; /** * Updates the value using a transformation function and waits for all observer callbacks to complete. * @param updateFn - Function that receives the current value and returns the new value * @returns {Promise<this>} */ updateAsync(updateFn: (current: T) => T): Promise<this>; /** * Subscribes to value changes and immediately receives the current value. * @param fn - Function to be called with the current value and subsequent changes * @returns {() => void} A cleanup function that removes the event handler */ subscribe(fn: (value: T) => void): () => void; /** * Registers a function to be called when the value changes. * @param fn - Function to be called with the new value * @returns {() => void} A cleanup function that removes the event handler */ onChange(fn: (value: T) => void): () => void; /** * Checks if there are any active subscribers. * @returns {boolean} True if there are any subscribers, false otherwise */ hasObservers(): boolean; /** * Returns the number of active subscribers. * @returns {number} The number of active subscribers */ observerCount(): number; /** * Creates a derived ObservableValue that updates whenever this one changes. * @template U The type of the derived value * @param transform - Function to transform the value * @returns {ObservableValue<U>} A new ObservableValue instance */ map<U>(transform: (value: T) => U): ObservableValue<U>; }