Skip to content

withSubscribe

withSubscribe<T, E>(target: T & Partial<{ subscribe: SubscribeFunc<E>; }>): T & { subscribe: SubscribeFunc<E>; }

Defined in: extras/with-subscribe.ts:30

Enhances a StateMachine with a subscribe method for event notifications. Powered by emitter, this function allows external code to subscribe to events emitted by the state machine.

Use cases:

  • Adding pub/sub capability to state machines
  • Allowing external listeners to react to state changes or events
  • Useful for event-driven architectures and reactive programming
Type ParameterDescription
T extends Pick<StateMachine<any>, "notify">The StateMachine type with a notify method
E extends anyThe event type handled by notify
ParameterTypeDescription
targetT & Partial<{ subscribe: SubscribeFunc<E>; }>The state machine to enhance

T & { subscribe: SubscribeFunc<E>; }

The enhanced state machine with a subscribe method

const machine = { notify: (ev: string) => undefined };
const enhanced = withSubscribe(machine);
enhanced.subscribe((ev: string) => console.log('Event:', ev));
enhanced.notify('test'); // Logs: 'Event: test'

This function is useful for scenarios where you want to allow external code to subscribe to events or changes emitted by a state machine. It wraps the notify method to emit events to subscribers, enabling reactive patterns and decoupled event handling.

export const withSubscribe = <
T extends Pick<StateMachine<any>, "notify">,
E extends Parameters<T["notify"]>[0],
>(
target: T & Partial<{ subscribe: SubscribeFunc<E> }>
) => {
if (!target.subscribe) {
const notify = target.notify.bind(target);
const [subscribe, emit] = emitter<Parameters<T["notify"]>[0]>();
target.notify = (ev) => {
notify(ev);
emit(ev);
};
target.subscribe = subscribe;
}
return target as T & { subscribe: typeof target.subscribe };
};

emitter for the underlying pub/sub implementation