containerized-state
Version:
Fast and minimal state container which can be used and shared across React or non-React components.
66 lines (62 loc) • 2.25 kB
TypeScript
declare const Entity: {
readonly DEFAULT: "default";
readonly COMPUTED: "computed";
};
type CallableFunction<TArgs extends any[] = [], TReturn = void> = (...args: TArgs) => TReturn;
type SubscribeCallback<T> = (value: T) => Promise<void> | void;
type Unsubscribe = () => void;
type ComputeValue<T, P> = (value: T) => P;
type EqualityCheckFunction<P> = (prev: P, next: P) => boolean;
type ComputedEntity<T, P> = {
type: (typeof Entity)["COMPUTED"];
cb: SubscribeCallback<P>;
computeValue: ComputeValue<T, P>;
isEqual?: EqualityCheckFunction<P>;
};
type DefaultEntity<T> = {
type: (typeof Entity)["DEFAULT"];
cb: SubscribeCallback<T>;
};
type ContainerEntity<T> = DefaultEntity<T> | ComputedEntity<T, any>;
type Initializer<T> = T | CallableFunction<[], T>;
declare class Container<T> {
protected _value: T;
protected _subscribers: Set<ContainerEntity<T>>;
static create<T>(initializer: Initializer<T>): Container<T>;
constructor(initializer: Initializer<T>);
/**
* A snapshot of the state.
*/
getValue(): T;
/**
* Updates the value of the state and notifies the subscribers.
*/
setValue(newValue: T): Promise<void>;
/**
* Subscribes to the changes of the container's state value
* and returns the unsubscribe function.
*/
subscribe(cb: SubscribeCallback<T>, options?: {
/**
* An `AbortSignal` reference to control the unsubscibe.
*/
signal?: AbortSignal;
}): Unsubscribe;
/**
* Subscribes to the changes of the container's selected state values
* and returns the unsubscribe function.
*
* For more control over emission changes, you may provide a custom equality function.
*/
computedSubscribe<P>(computeValue: ComputeValue<T, P>, cb: SubscribeCallback<P>, options?: {
/**
* An `AbortSignal` reference to control the unsubscibe.
*/
signal?: AbortSignal;
/**
* A custom equality function to control emission changes.
*/
isEqual?: EqualityCheckFunction<P>;
}): Unsubscribe;
}
export { type ComputeValue, Container, type EqualityCheckFunction, type Initializer, type SubscribeCallback, type Unsubscribe };