Producers
A producer is an effect function* that emits values with yield, runs Effects with try between yields, and compiles directly to an Effect Stream. Consume any Stream — from a producer or from Effect's Stream constructors — with for try.
Yielding values on demand (effect function* + for try)
effect function* readings() {
try addFinalizer(() => Console.log("sensor closed"))
for (const celsius of [18, 21, 25, 19, 28, 30]) {
yield celsius
}
}
effect function firstAlert() {
let alert: number | undefined
for try (const celsius of readings()) {
if (celsius >= 25) {
alert = celsius
break
}
}
return alert
}
// Inferred: (number | undefined)!!
// Run in an effect function: try Console.log(try firstAlert())
// Output: sensor closed
// Output: 25- Calling
readings()constructs a lazyStream.Stream<number>without running its body. - Each
yield xoffers one element and pauses under backpressure. The producer can run up to two elements ahead of its consumer: one in its one-element buffer and one waiting to be offered. This bound is for one sequential emitter. In afor concurrentbody, each active item can compute its value before waiting to offer it, so the buffer does not bound all pending offers or upstream work. - The producer supplies its own
Scope. For inferred body requirementsRBody, the Stream requiresExclude<RBody, Scope.Scope>, soaddFinalizer,acquireRelease, andfork.scopedinside it add nothing toR.Scope.Scope | UsersbecomesUsers; other service requirements remain. breakor a failure infor trycloses the Stream and runs all producer finalizers (sensor closed) before returning.
Calling services between yields
import * as NodeServices from "@effect/platform-node/NodeServices"
effect function* fileTexts(directory: string) {
const fs = try FileSystem.FileSystem
const path = try Path.Path
const names = (try fs.readDirectory(directory)).sort()
for (const name of names) {
const filename = path.join(directory, name)
const info = try fs.stat(filename)
if (info.type === "File") {
yield { path: filename, text: try fs.readFileString(filename) }
}
}
}
effect function firstLargeFile(directory: string) {
let found: string | undefined
for try (const file of fileTexts(directory)) {
if (file.text.length > 1000) {
found = file.path
break
}
}
return found
}
// Run in an effect function: provide NodeServices.layer { try scoped(effect { const fs = try FileSystem.FileSystem; const dir = try fs.makeTempDirectoryScoped(); try fs.writeFileString(`${dir}/a.txt`, "short"); try fs.writeFileString(`${dir}/b.txt`, try Effect.try(() => "x".repeat(1001))); try Console.log((try firstLargeFile(dir)) === `${dir}/b.txt`) }) }
// Output: trueAny service read with try (FileSystem, Path) and any error thrown inside the producer flow straight into the returned Stream's E and R channels.
Composing producers with Stream operators
Because a producer is a Stream.Stream<A, E, R>, every Effect Stream operator works on it directly:
effect function alerts() {
const selected = readings()
|> Stream.filter(%, (value) => value >= 25)
|> Stream.map(%, (value) => `${value} C`)
|> Stream.take(%, 2)
const result: string[] = []
for try (const alert of selected) result.push(alert)
return result
}
// Run in an effect function:
// {
// const jsonValue = try alerts()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: sensor closed
// Output: ["25 C","28 C"]Consuming any Stream with for try
effect function sumStream() {
let total = 0
for try (const value of Stream.fromIterable([1, 2, 3])) {
total += value
}
return total
}
// Run in an effect function: try Console.log(try sumStream())
// Output: 6Rules for for try and producers:
| Construct | Rules & diagnostics |
|---|---|
effect function* / effect *method() | Bare return ends the stream; return value is EK2128. yield* is EK2103 — forward another stream with for try (const x of other) yield x. Non-Stream return annotation is EK2102. yield inside a non-producer effect function is EK2104. |
for try (const x of stream) | Valid only in effect code (EK2001). Operand must be a Stream (EK2004). Head must use const or let (EK2005). continue skips an item; break closes the stream; return (EK2002) and labeled jumps outside the loop (EK2003) are errors — save into a variable and break. |
Fibers inside for try | Each item runs on the current consuming fiber. A plain fork inside the body is owned by that fiber: it may outlive its item and the loop, is never implicitly joined, and is interrupted when its owner ends. fork.in, fork.scoped, and fork.detached keep their own owners. |
Native iteration and cleanup
Ordinary for...of and array destructuring keep ECMA-262 semantics: the native algorithm determines which completions close an iterator, and an exhausted iterator is not closed again. Effect failure is different. An Effect run by try that fails, dies or is interrupted abandons the generator, so neither its iterator closing nor using disposal runs. For cleanup on every exit, use scoped with acquireRelease.
Plain JavaScript generators (function*)
A plain function* (without effect) stays an ordinary JavaScript generator for Iterator APIs and Effect.gen. Passing a producer where a JS generator is expected reports EK1002:
function* countdown(from: number): Generator<number> {
for (let n = from; n > 0; n--) yield n
}
// Run in an effect function: try Console.log([...countdown(3)].join(","))
// Output: 3,2,1Coming from Effect
effect function* replaces manual Stream.callback plumbing, and for try replaces Stream.runForEachWhile. Use try for Effects and yield exclusively for emitted Stream elements.