Resourceful Streams
A stream can own a file handle, database cursor, or network subscription for the exact duration of its consumption. Acquire the resource lazily with acquireRelease inside the stream and close its lifetime with Stream.scoped: normal completion, early termination (Stream.take), failure, and interruption all trigger release deterministically.
Acquiring for the stream lifetime
effect function openReader() {
try Console.log("reader opened")
return { lines: ["header", "entry-a", "entry-b"] }
}
const lines = Stream.fromEffect(acquireRelease(
openReader(),
() => Console.log("reader closed")
)).pipe(
Stream.flatMap((reader) => Stream.fromArray(reader.lines)),
Stream.scoped
)
effect function readLines() {
return try Stream.runCollect(lines)
}
// Run in an effect function:
// {
// const jsonValue = try readLines()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: reader opened
// Output: reader closed
// Output: ["header","entry-a","entry-b"]Three pieces cooperate here:
acquireRelease(open, close)pairs acquisition with cleanup in the activeScope.Stream.fromEffect(...)defers acquisition until a consumer pulls—defininglinesopens nothing, and each consumption acquires a fresh handle.Stream.scopedprovides and closes thatScopearound the entire downstream pipeline, so every stage usingreaderstays inside the resource's lifetime.
Release after stopping or interruption
effect function readHeader() {
return try Stream.runCollect(Stream.take(lines, 1))
}
// Returns ["header"] and closes the reader.
effect function readWithDeadline() {
return try timeout(
Stream.runForEach(lines, effect (line) => {
try sleep("1 second")
try Console.log(line)
}),
"100 millis"
)
}
// Run in an effect function:
// {
// const jsonValue = try readHeader()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// const outcome = try result(readWithDeadline())
// if (Result.isFailure(outcome)) try Console.log(outcome.failure._tag)
// Output: reader opened
// Output: reader closed
// Output: ["header"]
// Output: reader opened
// Output: reader closed
// Output: TimeoutErrorWhether consumption stops early after one line (Stream.take(lines, 1)) or is interrupted by timeout, the runtime runs the release finalizer before returning or reporting TimeoutError.
Avoid acquiring a resource inside an outer scoped(effect { ... }) that merely returns a lazy Stream: that outer scope closes as soon as the Effect returns, releasing the resource before the stream is ever pulled. Acquire stream-owned resources inside the stream.
Registering finalizers
const audited = Stream.ensuring(lines, effect {
try Console.log("reader resources released")
try Console.log("consumption finished")
})
effect function readAudited() {
return try Stream.runCollect(audited)
}
// Run in an effect function:
// {
// const jsonValue = try readAudited()
// try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
// }
// Output: reader opened
// Output: reader closed
// Output: reader resources released
// Output: consumption finished
// Output: ["header","entry-a","entry-b"]Stream.ensuring runs an infallible Effect (E = never) after the wrapped stream's own finalizers on every exit. Wrap the cleanup in effect { ... } so it executes at finalization rather than stream construction. Handle expected cleanup errors inside the finalizer; any defect still propagates in the exit Cause.
Coming from Effect
- Keep
Stream.fromEffect,Stream.scoped, andStream.ensuringto bind resource lifetimes to stream execution. - Use
try scoped(effect { ... })for resources owned by the consuming function itself; useStream.fromEffect(acquireRelease(...))+Stream.scopedfor resources owned by the stream.
The matching Effect page: effect.website/docs/v4/stream/resourceful-streams