Skip to content

producer()

Creates a general-purpose reactive source with emit, signal, complete, and error. The optional factory runs on first subscriber; its return value is cleanup on last disconnect.

Signature

ts
function producer<T>(
	fn: ProducerFn<T> | undefined,
	opts: ProducerOpts<T> & { initial: T },
): ProducerStore<T> & Store<T>
function producer<T>(fn?: ProducerFn<T>, opts?: ProducerOpts<T>): ProducerStore<T>

Parameters

ParameterTypeDescription
fnProducerFn&lt;T&gt;Optional setup function receiving action callbacks; return teardown on disconnect.
optsProducerOpts&lt;T&gt;Optional configuration (initial value, equality, autoDirty, getter, etc.).

ProducerOpts

PropertyTypeDefaultDescription
initialTundefinedValue before first emit; reset target when resetOnTeardown.
equals(a: T, b: T) =&gt; booleanundefinedSkips emit when new value equals cached.
autoDirtybooleantrueSend DIRTY on STATE before each DATA emission.
getter(cached) =&gt; TundefinedPull-based recompute when disconnected.
resetOnTeardownbooleanfalseReset to initial when last sink disconnects.
resubscribablebooleanfalseAllow new subscriptions after complete/error.
namestringundefinedDebug name for Inspector.

Returns

ProducerStore&lt;T&gt; — a store with:

MethodSignatureDescription
get()() =&gt; T \undefined
emit(value)(value: T) =&gt; voidPushes a new value to subscribers.
signal(s)(s: Signal) =&gt; voidSends DIRTY or RESOLVED on the STATE channel.
complete()() =&gt; voidEnds the stream successfully.
error(e)(e: unknown) =&gt; voidEnds the stream with an error.
sourcecallbagUnderlying callbag source for subscriptions.

Basic Usage

ts
import { producer } from 'callbag-recharge';

const bus = producer<string>();
bus.emit('a');
bus.get(); // 'a'

Options / Behavior Details

  • Lazy start: No work until the first source() subscription.
  • Tier 2 boundary: Used by async/timer operators; each emit starts a new DIRTY+value cycle when autoDirty is true.

Examples

Factory with cleanup

ts
const ticks = producer<number>(({ emit, complete }) => {
    let n = 0;
    const id = setInterval(() => {
        emit(n++);
        if (n >= 3) complete();
      }, 10);
  return () => clearInterval(id);
});

See Also

Released under the MIT License.