Skip to content

@epikodelabs/streamix


@epikodelabs/streamix / src/public-api / unfold

Function: unfold() ​

unfold<State, Value>(initialState, step): AsyncIterable<Value>

Defined in: projects/libraries/streamix/src/lib/factories/unfold.ts:39

Creates a truly pull-driven async iterable from a state machine.

One call to iterator.next() evaluates at most one step and produces at most one value. The transition (step.next) is deferred until the following pull. No timer, microtask, subscription, or background producer is started by this factory. Each iterator has its own state and AbortController.

return() and throw() abort the signal supplied to step and next. As with other async iterables, an asynchronous callback must cooperate with that signal for prompt cancellation while a pull is pending.

Wrap the result with flow(unfold(...)) when an Atom is needed. Note that flow() drives its source while subscribed, so that wrapper does not retain one-pull-per-downstream-next semantics.

Type Parameters ​

State ​

State

Value ​

Value

Parameters ​

initialState ​

State

step ​

(state, signal) => MaybePromise<UnfoldStep<State, Value> | null>

Returns ​

AsyncIterable<Value>

Example ​

ts
const numbers = unfold(0, n => n < 3
  ? { value: n, next: () => n + 1 }
  : null);

for await (const number of numbers) console.log(number); // 0, 1, 2

Released under the MIT License.