Skip to content

Choosing operators ​

Use the catalog for individual examples and API links. Choose how values should flow before setting concurrency or timing limits.

GoalOperatorsBehavior
Transform or select itemsmap, filter, filterMapmap supports concurrency; the others run sequentially.
Limit output or group itemstake, chunks, bufferTimeCount at the stage's position; see processing order.
Join known sources in sequencechain(a, b)Closes each source before opening the next.
Interleave known sourcesmerge(a, b)Reads sources concurrently.
Flatten a stream of sourcesconcat, flattenconcat preserves child order; flatten interleaves ready children.
Create a source per itemconcatMap, flatMapOrdered or interleaved flattening after a synchronous mapper. Use defer for async setup.
Pair corresponding valueszip(a, b)Stops when the shortest source ends.
Combine current valueszipLatest([a, b])Waits for every source's first value; partial: true fills missing values with undefined.

concat, flatten, concatMap, and flatMap default to concurrency: 1. Increase it to overlap children; ordered variants still deliver each child's output in sequence. See concurrency bounds.

For pacing and deadlines, use the timing guide. For retries and fallback sources, use error handling. Choose a terminal consumer to start reading.

broadcast sends the same values to every active branch; route sends each item to at most one branch. Both run the source once and bound each branch queue.

Accumulated state ​

scan emits each updated accumulator; reduce returns only the final one. Both await the initial value and reducer results. An empty input emits nothing from scan, while reduce returns the initial value.

Objects are passed by reference, not copied. Use immutable updates for snapshots. If you mutate state, create it inside defer for each execution and capture each result before the next mutation:

ts
import { defer, from } from "mogami-stream";

export const totals = defer(() =>
  from([1, 2])
    .scan(
      (state, value) => {
        state.total += value;
        return state;
      },
      { total: 0 },
    )
    .map((state) => state.total),
);
console.log(await totals.toArray()); // [1, 3]
console.log(await totals.toArray()); // [1, 3]

Promise-valued items ​

from and selection/combination operators preserve Promise objects as items. Unlike native for await over a synchronous iterable, they do not unwrap those items. Use map to await them:

ts
export const pending = Promise.resolve(2);
export const preserved = await from([pending]).toArray(); // [Promise<2>]
export const resolved = await from([pending])
  .map((value) => value)
  .toArray(); // [2]

find receives the original item in its predicate, but awaits a matched Promise when returning it.

Select ranges and moving windows ​

slice(start, end) selects a range with an inclusive start and exclusive end. Omitting start uses zero; omitting end reads to completion. Bounds must be safe integers: fractions, NaN, and infinities throw RangeError. With non-negative bounds, slice(2, 5) skips two items, emits three, and closes upstream before delivering the final selected item. Ranges known to be empty, such as slice(5, 2), do not open upstream.

Negative bounds count from the end. slice(2, -3) emits after a three-item delay while retaining only those three trailing items. slice(-5) and slice(-5, -2) wait for input completion and retain at most five items. A negative start therefore requires finite input.

slidingWindow(size) emits overlapping arrays, advancing one item at a time. It waits for a full window and omits incomplete windows; size must be a positive safe integer. Unlike chunks, adjacent windows share items. Each output array is independent, although its elements retain their original identities. Internal storage is bounded by size; producing each snapshot takes O(size) work.

ts
const averages = await from([1, 2, 3, 4, 5])
  .slidingWindow(3)
  .map(
    (window) => window.reduce((sum, value) => sum + value, 0) / window.length,
  )
  .toArray(); // [2, 3, 4]

Use at when only one position is needed, or finish a selected range with toArray(), count(), or drain().