Creating Streams
A Stream is a lazy blueprint for producing zero or more elements on demand. Constructing a stream performs no work and acquires no resources; effectful callbacks run only when a consumer pulls from it. See the introduction for stream fundamentals and effect function* producers.
| Source | Constructors |
|---|---|
| Values & sequences | make, empty, succeed, fail, range, iterate |
| Collections & iterables | fromArray, fromArrays, fromIterable, fromIterableEffect, fromAsyncIterable |
| Effects & push callbacks | fromEffect, callback, scoped |
| Repetition & time | forever, repeat, fromEffectRepeat, tick, fromSchedule, fromEffectSchedule |
| Stateful generation | unfold, paginate |
| Concurrency primitives | fromQueue, fromPubSub |
Finite and empty streams
const labels = Stream.make("queued", "running", "complete")
const absent = Stream.empty
const signal = Stream.succeed(void 0)
const pages = Stream.range(4, 7)
const powers = Stream.take(Stream.iterate(2, (n) => n * 2), 4)
effect function readPowers() {
return try Stream.runCollect(powers) // [2, 4, 8, 16]
}
// Run in an effect function:
// {
// const jsonValue = [try Stream.runCollect(labels), try Stream.runCollect(absent), try Stream.runCount(signal), try Stream.runCollect(pages), try readPowers()]
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: [["queued","running","complete"],[],1,[4,5,6,7],[2,4,8,16]]make emits its arguments in order; empty completes immediately with no elements; range(start, end) is inclusive on both ends. iterate(initial, next) emits initial and applies its pure step indefinitely—always bound infinite streams (for example, with Stream.take) before collecting.
Successes and failures
error SourceClosed
const ready = Stream.succeed("ready")
const closed = Stream.fail(new SourceClosed())
effect function readClosed() {
return Stream.runCollect(closed) catch (error) => match (error) {
when SourceClosed: ["source unavailable"];
}
}
// Run in an effect function:
// {
// const jsonValue = [try Stream.runCollect(ready), try readClosed()]
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: [["ready"],["source unavailable"]]Stream.succeed emits one value and ends; Stream.fail constructs a stream that fails on consumption without throwing at definition time. Handle its typed failure with stream recovery operators or a catch expression on the consuming Effect.
Arrays and iterables
const fromArray = Stream.fromArray([11, 22])
const fromBatches = Stream.fromArrays([11, 22], [33])
const fromSet = Stream.fromIterable(new Set(["east", "west"]))
service Catalog {
codes(): ReadonlyArray<string>!!
}
const codes = Stream.fromIterableEffect(effect {
const catalog = try Catalog
return try catalog.codes()
})
// Run in an effect function: provide Catalog = { codes: effect () => ["A", "B"] } { { const jsonValue = [try Stream.runCollect(fromArray), try Stream.runCollect(fromBatches), try Stream.runCollect(fromSet), try Stream.runCollect(codes)]; try Console.log(try Effect.try(() => JSON.stringify(jsonValue))) } }
// Output: [[11,22],[11,22,33],["east","west"],["A","B"]]fromArray and fromIterable emit collection elements; fromArrays preserves each array as an internal chunk boundary. fromIterableEffect defers computing the iterable until consumption, carrying any service requirements into the stream's R parameter.
Async iterables
// TypeScript (.ts)
// rows.ts
/** @throws {never} */
export function rows(fail = false): AsyncIterable<string> {
return {
async *[Symbol.asyncIterator]() {
if (fail) throw new Error("iterator failed")
yield "row-a"
yield "row-b"
}
}
}
// Run: return (async () => { const values = []; for await (const row of rows()) values.push(row); console.log(JSON.stringify(values)); try { for await (const row of rows(true)) {} } catch (error) { console.log((error as Error).message) } })()
// Output: ["row-a","row-b"]
// Output: iterator failedimport { rows } from "./rows.js"
error IteratorFailed {
cause: unknown
}
function adaptRows(rows: AsyncIterable<string>) {
return Stream.fromAsyncIterable(rows, (cause) => new IteratorFailed({ cause }))
}
// Run in an effect function:
// {
// const jsonValue = try Stream.runCollect(adaptRows(rows()))
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// const outcome = try result(Stream.runCollect(adaptRows(rows(true))))
// if (Result.isFailure(outcome)) try Console.log(outcome.failure._tag)
// Output: ["row-a","row-b"]
// Output: IteratorFailedStream.fromAsyncIterable bridges a JavaScript AsyncIterable from a TypeScript adapter or service into an Effect Stream. @throws {never} on rows declares only that constructing the iterable does not throw; the second argument maps rejections thrown during iteration into the stream's typed error channel.
Effects and callbacks
const timestamp = Stream.fromEffect(Clock.currentTimeMillis)
const notices = Stream.callback<string>(effect (queue) => {
try Queue.offer(queue, "connected")
try Queue.offer(queue, "ready")
try Queue.end(queue)
})
effect function readNotices() {
return try Stream.runCollect(notices) // ["connected", "ready"]
}
// Run in an effect function:
// const clock = try Clock.Clock
// provide Clock.Clock = { ...clock, currentTimeMillis: succeed(123), currentTimeMillisUnsafe: () => 123 } { { const jsonValue = [try Stream.runCollect(timestamp), try readNotices()]; try Console.log(try Effect.try(() => JSON.stringify(jsonValue))) } }
// Output: [[123],["connected","ready"]]Stream.fromEffect emits a single Effect's result. Stream.callback bridges push-style producers via a bounded queue: call Queue.offer to emit, Queue.end to complete, and Queue.fail to signal a typed error. Pass { bufferSize, strategy } ("suspend", "dropping", or "sliding") as the optional second argument to control backpressure.
For external event listeners, register and unregister the listener with Effect.acquireRelease inside a TypeScript adapter; the callback's Scope remains open for the stream's lifetime. Because synchronous platform callbacks cannot run try, invoke an Effect runner at the adapter boundary when a listener needs to start work.
Scoped sources
effect function openSession() {
try Console.log("open session")
return try acquireRelease(
succeed({ name: "metrics" }),
() => Console.log("close session")
)
}
const sessionNames = Stream.fromEffect(openSession()).pipe(
Stream.map((session) => session.name),
Stream.scoped
)
// Run in an effect function:
// {
// const jsonValue = try Stream.runCollect(sessionNames)
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: open session
// Output: close session
// Output: ["metrics"]Stream.scoped closes the stream's Scope as soon as consumption ends, fails, or is interrupted, running every finalizer registered with acquireRelease. Place all stages that depend on the resource before Stream.scoped; see Resourceful Streams.
Repeating values, streams, and effects
const pings = Stream.forever(Stream.succeed("ping"))
const rounds = Stream.repeat(Stream.make("start", "finish"), Schedule.recurs(2))
const times = Stream.fromEffectRepeat(Clock.currentTimeMillis)
effect function countdown() {
let remaining = 3
const source = Stream.fromEffectRepeat(effect {
if (remaining === 0) try Cause.done()
return remaining--
})
return try Stream.runCollect(source) // [3, 2, 1]
}
// Run in an effect function:
// {
// const jsonValue = [try Stream.runCollect(Stream.take(pings, 3)), try Stream.runCollect(rounds), try Stream.runCount(Stream.take(times, 2)), try countdown()]
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: [["ping","ping","ping"],["start","finish","start","finish","start","finish"],2,[3,2,1]]forever repeats a stream endlessly; repeat(stream, schedule) runs the stream once plus every repetition permitted by schedule (Schedule.recurs(2) yields three passes total). fromEffectRepeat re-evaluates an Effect for each element and terminates cleanly when the Effect signals Cause.Done via try Cause.done(). Keep mutable per-run state inside an enclosing function (as in countdown) so independent consumptions never share it.
Periodic elements
const samples = Stream.mapEffect(Stream.tick("250 millis"), () => Clock.currentTimeMillis)
effect function collectSamples() {
return try Stream.runCollect(Stream.take(samples, 4))
}
// Run in an effect function:
// const values = try collectSamples()
// try Console.log(values.length, values.every(Number.isFinite))
// Output: 4 trueStream.tick(interval) emits void on a fixed cadence; pair it with Stream.mapEffect to sample on each tick. Because streams are pull-based, slow downstream stages apply backpressure rather than accumulating unbounded ticks.
Unfolding state and paginating responses
const halving = Stream.unfold(32, effect (n) => {
if (n < 2) return undefined
return [n, n / 2] as const
})
service Directory {
page(cursor: number): {
names: ReadonlyArray<string>
next: number | undefined
}!!
}
const names = Stream.paginate(0, effect (cursor) => {
const directory = try Directory
const page = try directory.page(cursor)
return [page.names, Option.fromUndefinedOr(page.next)] as const
})
// Run in an effect function: provide Directory = { page: effect (cursor) => ({ names: [String(cursor)], next: cursor < 2 ? cursor + 1 : undefined }) } { { const jsonValue = [try Stream.runCollect(halving), try Stream.runCollect(names)]; try Console.log(try Effect.try(() => JSON.stringify(jsonValue))) } }
// Output: [[32,16,8,4,2],["0","1","2"]]Stream.unfold steps one element at a time: return [element, nextState] to emit and continue, or undefined to stop without emitting. Stream.paginate fetches whole batches: return [batch, Option.some(nextCursor)] to continue, or [batch, Option.none()] to emit the final page and end.
Queues and broadcasts
effect function queuedNumbers() {
const queue = try Queue.unbounded<number, Cause.Done>()
try Queue.offer(queue, 8)
try Queue.offer(queue, 13)
try Queue.end(queue)
return try Stream.runCollect(Stream.fromQueue(queue)) // [8, 13]
}
function fromBroadcast(bus: PubSub.PubSub<string>) {
return Stream.fromPubSub(bus)
}
// Run in an effect function:
// {
// const jsonValue = try queuedNumbers()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// const bus = try PubSub.unbounded<string>({ replay: 1 })
// try PubSub.publish(bus, "broadcast")
// {
// const jsonValue = try Stream.runCollect(Stream.take(fromBroadcast(bus), 1))
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: [8,13]
// Output: ["broadcast"]Stream.fromQueue creates a work-sharing stream—multiple consumers pull competing elements from the same queue. Stream.fromPubSub creates a fan-out stream—each consumption opens its own subscription and receives every element published while subscribed (plus any configured replay buffer).
Schedules as sources
const policy = Schedule.spaced("400 millis").pipe(Schedule.upTo({ times: 3 }))
const pulses = Stream.fromSchedule(policy)
effect function readPulses() {
return try Stream.runCollect(pulses) // [0, 1, 2]
}
// Run in an effect function:
// {
// const jsonValue = try readPulses()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: [0,1,2]Stream.fromSchedule(schedule) emits each schedule output until the schedule stops. Stream.fromEffectSchedule(work(), schedule) runs an Effect on that cadence and emits its results. Both carry the schedule's timing and service requirements.
The matching Effect page: effect.website/docs/v4/stream/creating