Operations
Stream operators are lazy pipeline transformers: each takes one or more streams and returns a new stream description without pulling any data. Keep pure stages synchronous (map, filter, scan); reach for *Effect variants only when a stage calls services, waits, or can fail.
Observing and taking elements
const observed = Stream.tap(Stream.range(10, 18), (n) => log(`reading ${n}`))
const first = Stream.take(observed, 3)
const below = Stream.takeWhile(observed, (n) => n < 13)
const through = Stream.takeUntil(observed, (n) => n === 13)
const last = Stream.takeRight(observed, 2)
effect function readFirst() {
return try Stream.runCollect(first) // [10, 11, 12]
}
// Run in an effect function: try Effect.provide(effect { { const jsonValue = try readFirst(); try Console.log(try Effect.try(() => JSON.stringify(jsonValue))) }; provide Logger.layer([]) { { const jsonValue = [try Stream.runCollect(below), try Stream.runCollect(through), try Stream.runCollect(last)]; try Console.log(try Effect.try(() => JSON.stringify(jsonValue))) } } }, Logger.layer([Logger.withConsoleLog(Logger.make(({ message }) => (message as unknown[])[0]))]))
// Output: reading 10
// Output: reading 11
// Output: reading 12
// Output: [10,11,12]
// Output: [[10,11,12],[10,11,12,13],[17,18]]tap runs a side-effecting observer without altering elements. takeWhile stops before the first element that fails its predicate; takeUntil includes the first element that matches, then stops. takeRight must buffer until the source terminates, so never apply it to infinite streams. takeWhileEffect and takeUntilEffect accept effectful predicates; any failure in a tap or predicate fails the stream.
Async iteration and manual pulls
// TypeScript (.ts)
// exporter.ts
import { Effect } from "effect"
/** @throws {never} */
export function countRows(rows: AsyncIterable<string>): Effect.Effect<number, Error> {
return Effect.tryPromise({
try: async () => {
let count = 0
for await (const row of rows) count++
return count
},
catch: (cause) => cause instanceof Error ? cause : new Error(String(cause))
})
}
// Run: return Effect.runPromise(countRows({ async *[Symbol.asyncIterator]() { yield "a"; yield "b" } })).then((count) => console.log(count))
// Output: 2import { countRows } from "./exporter.js"
service Exporter {
write(rows: AsyncIterable<string>): number!Error
}
effect function exportRows(source: Stream.Stream<string>) {
const rows = try Stream.toAsyncIterableEffect(source)
const exporter = try Exporter
return try exporter.write(rows)
}
// Run in an effect function: provide Exporter = { write: (rows) => countRows(rows) } { try Console.log(try exportRows(Stream.make("a", "b"))) }
// Output: 2try Stream.toAsyncIterableEffect(source) captures active services and adapts a stream into an AsyncIterable for TypeScript libraries (use Stream.toAsyncIterable when R = never). Conversion pulls nothing on its own; stream errors surface as thrown JS errors inside for await, so the adapter must map them back into its declared error type.
effect function printBatches() {
try scoped(effect {
const pull = try Stream.toPull(Stream.rechunk(Stream.range(30, 34), 2))
while (true) {
const batch = try Pull.catchDone(pull, () => succeed(undefined))
if (batch === undefined) break
{ const jsonValue = batch; try Console.log(try Effect.try(() => JSON.stringify(jsonValue))) }
}
})
}
// Run in an effect function: try printBatches()
// Output: [30,31]
// Output: [32,33]
// Output: [34]try Stream.toPull(source) exposes the underlying scoped chunk-pull Effect: each try pull yields a non-empty array or ends with Cause.Done (caught here via Pull.catchDone). Keep pull strictly inside its scoped block. For everyday consumption, prefer Stream.run* consumers or for try (const element of source) { ... }, which manages the pull and closes the stream on loop exit (including for effect function* streams).
Mapping, flattening, and state
effect function loadLabel(id: number) {
try sleep("10 millis")
return `item-${id}`
}
const labels = Stream.mapEffect(Stream.make(4, 7, 9), (id) => loadLabel(id), { concurrency: 2 })
const upper = Stream.map(labels, (label) => label.toUpperCase())
const signals = Stream.map(labels, () => null)
const words = Stream.make("red green", "blue").pipe(
Stream.map((line) => line.split(" ")),
Stream.flattenIterable
)
const totals = Stream.mapAccum(Stream.make(4, 7, 9), () => 0, (total, n) => {
const next = total + n
return [next, [next]] as const
})
// Run in an effect function:
// {
// const jsonValue = [try Stream.runCollect(labels), try Stream.runCollect(upper), try Stream.runCollect(signals), try Stream.runCollect(words), try Stream.runCollect(totals)]
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: [["item-4","item-7","item-9"],["ITEM-4","ITEM-7","ITEM-9"],[null,null,null],["red","green","blue"],[4,11,20]]map transforms synchronously; mapEffect runs an Effect per element. With concurrency > 1, mapEffect preserves input order unless { unordered: true } is set. flattenIterable expands each emitted iterable into individual elements. mapAccum (and mapAccumEffect) threads fresh per-run state through [nextState, emittedValues] tuples, letting each input emit zero, one, or many outputs. Use Stream.drain to execute effects while discarding emitted values.
Filtering, scanning, and changes
const readings = Stream.make(2, 2, 5, 5, 2)
const large = Stream.filter(readings, (n) => n >= 5)
const changes = Stream.changes(readings)
const running = Stream.scan(readings, () => 0, (total, n) => total + n)
effect function inspect() {
return {
large: try Stream.runCollect(large), // [5, 5]
changes: try Stream.runCollect(changes), // [2, 5, 2]
running: try Stream.runCollect(running) // [0, 2, 4, 9, 14, 16]
}
}
// Run in an effect function:
// {
// const jsonValue = try inspect()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: {"large":[5,5],"changes":[2,5,2],"running":[0,2,4,9,14,16]}filter keeps matching elements; scan emits the seed plus every intermediate accumulator (unlike runFold, which emits only the final result). changes suppresses adjacent duplicates only—it does not deduplicate globally. All three have *Effect variants, and changesWith accepts a custom equality predicate.
Zipping and indexing
const sizes = Stream.make(5, 8, 13)
const names = Stream.make("small", "large")
const pairs = Stream.zip(sizes, names)
const descriptions = Stream.zipWith(sizes, names, (size, name) => `${name}: ${size}`)
const indexed = Stream.zipWithIndex(names)
const neighbors = Stream.zipWithPreviousAndNext(sizes)
effect function readPairs() {
return try Stream.runCollect(pairs) // [[5, "small"], [8, "large"]]
}
// Run in an effect function:
// {
// const jsonValue = [try readPairs(), try Stream.runCollect(descriptions), try Stream.runCollect(indexed), (try Stream.runCollect(neighbors)).map(([previous, value, next]) => [Option.getOrNull(previous), value, Option.getOrNull(next)])]
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: [[[5,"small"],[8,"large"]],["small: 5","large: 8"],[["small",0],["large",1]],[[null,5,8],[5,8,13],[8,13,null]]]zip and zipWith pair streams element-by-element and end when the shorter stream ends. zipWithIndex attaches zero-based positions; zipWithPrevious, zipWithNext, and zipWithPreviousAndNext supply neighbor context using Option.none() at the edges. For mismatched production rates, zipLatest / zipLatestWith wait until both sides emit once, then pair every new arrival with the other side's latest value.
Cartesian products
const variants = Stream.cross(Stream.make("linen", "wool"), Stream.make("blue", "gray"))
const names = Stream.crossWith(
Stream.make("linen", "wool"),
Stream.make("blue", "gray"),
(fabric, color) => `${color} ${fabric}`
)
// Run in an effect function:
// {
// const jsonValue = [try Stream.runCollect(variants), try Stream.runCollect(names)]
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: [[["linen","blue"],["linen","gray"],["wool","blue"],["wool","gray"]],["blue linen","gray linen","blue wool","gray wool"]]cross and crossWith emit the Cartesian product of left and right streams. The right stream is re-executed from scratch for every left element, so an infinite right stream prevents the left side from ever advancing past its first element.
Partitioning and grouping
effect function partitionReadings() {
return try scoped(effect {
const [even, odd] = try Stream.partition(
Stream.range(10, 19),
Filter.fromPredicate((n: number) => n % 2 === 0),
{ capacity: 2 }
)
return try.all [Stream.runCollect(even), Stream.runCollect(odd)]
})
}
// Run in an effect function:
// {
// const jsonValue = try partitionReadings()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: [[10,12,14,16,18],[11,13,15,17,19]]Stream.partition splits one upstream execution into [passing, failing] streams inside a Scope (partitionEffect accepts a Filter.FilterEffect). Always consume both branches concurrently inside the scope—an unread branch fills its buffer and backpressures the other.
const requests = Stream.make(
{ region: "west", bytes: 10 },
{ region: "east", bytes: 20 },
{ region: "west", bytes: 15 }
)
const groups = Stream.groupByKey(requests, (request) => request.region)
const summaries = Stream.flatMap(groups, ([region, group]) =>
Stream.fromEffect(effect {
const bytes = try Stream.runFold(group, () => 0, (total, request) => total + request.bytes)
return { region, bytes }
}), { concurrency: "unbounded" })
const batches = Stream.grouped(requests, 2)
const timedBatches = Stream.groupedWithin(requests, 20, "1 second")
// Run in an effect function:
// {
// const jsonValue = [(try Stream.runCollect(summaries)).sort((a, b) => a.region.localeCompare(b.region)), try Stream.runCollect(batches), try Stream.runCollect(timedBatches)]
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: [[{"region":"east","bytes":20},{"region":"west","bytes":25}],[[{"region":"west","bytes":10},{"region":"east","bytes":20}],[{"region":"west","bytes":15}]],[[{"region":"west","bytes":10},{"region":"east","bytes":20},{"region":"west","bytes":15}]]]groupByKey (and effectful groupBy) demultiplexes elements into [key, groupStream] pairs—consume the inner streams concurrently so one stalled group does not block distribution. grouped(n) collects fixed-size arrays; groupedWithin(n, duration) flushes on whichever limit triggers first. Both emit any partial final batch on stream end.
Concatenating, merging, and interleaving
const primary = Stream.make("a1", "a2")
const secondary = Stream.make("b1", "b2", "b3")
const sequential = Stream.concat(primary, secondary)
const flattened = Stream.flatten(Stream.make(primary, secondary))
const expanded = Stream.flatMap(primary, (label) => Stream.make(label, label.toUpperCase()))
const merged = Stream.merge(primary, secondary, { haltStrategy: "both" })
const alternating = Stream.interleave(primary, secondary)
const selected = Stream.interleaveWith(primary, secondary, Stream.make(true, false, false, true, false))
// Run in an effect function:
// {
// const jsonValue = [try Stream.runCollect(sequential), try Stream.runCollect(flattened), try Stream.runCollect(expanded), (try Stream.runCollect(merged)).sort(), try Stream.runCollect(alternating), try Stream.runCollect(selected)]
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: [["a1","a2","b1","b2","b3"],["a1","a2","b1","b2","b3"],["a1","A1","a2","A2"],["a1","a2","b1","b2","b3"],["a1","b1","a2","b2","b3"],["a1","b1","b2","a2","b3"]]| Operator | Pull strategy | Order / concurrency |
|---|---|---|
concat / flatten | Exhaust left, then right | Strictly sequential |
flatMap | Expand each element into a sub-stream | Sequential by default, or concurrent via { concurrency } |
switchMap | Cancel prior sub-stream when new element arrives | Latest-wins (ideal for typeahead / live queries) |
merge | Emit from whichever side is ready | Concurrent; configure haltStrategy ("both", "left", "right", "either") |
interleave / interleaveWith | Alternate deterministically (or by boolean stream) | Deterministic; drains survivor when one ends |
Any source failure fails merge regardless of haltStrategy. Map heterogeneous streams to a shared union type before merging.
Separators and affixes
const fields = Stream.make("name", "email", "role")
const separated = Stream.intersperse(fields, ",")
const bracketed = Stream.intersperseAffixes(fields, { start: "[", middle: ",", end: "]" })
effect function formatFields() {
return try Stream.mkString(bracketed) // "[name,email,role]"
}
// Run in an effect function:
// try Console.log(try Stream.mkString(separated))
// try Console.log(try formatFields())
// Output: name,email,role
// Output: [name,email,role]intersperse inserts a delimiter between adjacent elements; intersperseAffixes also wraps the stream with start and end. Inserted values are ordinary stream elements visible to downstream stages.
Broadcasting and buffering
effect function shareReadings() {
return try scoped(effect {
const [totals, audit] = try Stream.broadcastN(Stream.range(1, 12), { n: 2, capacity: 3 })
return try.all [
Stream.runSum(totals),
Stream.runForEach(audit, effect (n) => {
try sleep("10 millis")
try Console.log(`audit ${n}`)
})
]
})
}
const buffered = Stream.buffer(Stream.range(1, 12), { capacity: 3 })
// Run in an effect function:
// {
// const jsonValue = try shareReadings()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// {
// const jsonValue = try Stream.runCollect(buffered)
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: audit 1
// Output: audit 2
// Output: audit 3
// Output: audit 4
// Output: audit 5
// Output: audit 6
// Output: audit 7
// Output: audit 8
// Output: audit 9
// Output: audit 10
// Output: audit 11
// Output: audit 12
// Output: [78,null]
// Output: [1,2,3,4,5,6,7,8,9,10,11,12]Stream.broadcastN executes one source and fans every element out to n scoped subscribers. Consume all subscribers concurrently inside the scope; with suspending buffers, the slowest subscriber paces upstream.
Stream.buffer decouples producer and consumer speeds for a single pipeline: { capacity: n } backpressures when full, "unbounded" removes bounds, strategy: "sliding" evicts oldest buffered items, and strategy: "dropping" rejects newest items.
Debouncing and throttling
const bursts = Stream.concat(Stream.make("c", "ca", "cat"), Stream.fromEffect(effect {
try sleep("300 millis")
return "cats"
}))
const settled = Stream.debounce(bursts, "100 millis")
const paced = Stream.range(1, 10).pipe(
Stream.rechunk(1),
Stream.throttle({
cost: (batch) => batch.length,
units: 2,
duration: "1 second",
strategy: "shape",
burst: 1
})
)
// Run in an effect function:
// {
// const jsonValue = [try Stream.runCollect(settled), try Stream.runCollect(paced)]
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: [["cat","cats"],[1,2,3,4,5,6,7,8,9,10]]debounce emits only the latest element after a quiet window of duration. throttle enforces a token bucket replenishing units per duration (plus burst): "shape" delays over-budget batches until tokens refill, while "enforce" drops them. Because cost charges per internal chunk, call Stream.rechunk(1) first when you need per-element pacing.
Scheduling delivery
const announcements = Stream.schedule(
Stream.make("prepare", "deploy", "verify"),
Schedule.spaced("500 millis")
)
effect function announce() {
try Stream.runForEach(announcements, (message) => Console.log(message))
}
// Run in an effect function: try announce()
// Output: prepare
// Output: deploy
// Output: verifyStream.schedule paces an existing stream's emissions according to a Schedule (terminating early if the schedule finishes). For generating elements on a timer rather than pacing an existing stream, use Stream.tick or Stream.fromEffectSchedule.
The matching Effect page: effect.website/docs/v4/stream/operations