Skip to content

Creating Sinks

Pick the Sink constructor matching the reduction or side effect you need, then run it with try Stream.run(source, sink). Sinks are stateless blueprints—stateful initializers run fresh on every consumption, so one Sink value can be reused safely across streams. See Sink builders for the Sink type signature; effectful callbacks below use effect functions.

GoalConstructors
Pick endpoints or prefixeshead, last, take, takeWhile, takeUntil
Summarize or discardcount, sum, drain, timed, withDuration
Run side effects per elementforEach, forEachWhile, forEachArray
Finish immediatelysucceed, fail, fromEffect
Collect or reducecollect, reduce, reduceWhile, reduceEffect, fold, foldUntil

Basic consumers and endpoint values

effect function endpoints() {
  const source = Stream.make("opening", "middle", "closing")
  return {
    first: try Stream.run(source, Sink.head<string>()),
    last: try Stream.run(source, Sink.last<string>()),
    prefix: try Stream.run(source, Sink.take<string>(2))
  }
}
// first: Some("opening"), last: Some("closing")
// prefix: ["opening", "middle"]
// Run in an effect function:
//   {
//     const jsonValue = [Option.getOrElse((try endpoints()).first, () => ""), Option.getOrElse((try endpoints()).last, () => ""), (try endpoints()).prefix]
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
// Output: ["opening","closing",["opening","middle"]]

head completes on the first element; last drains the stream to capture the final element. Both return Option.none() on empty streams. take(n) collects up to n elements, stops early at n, and keeps any unused elements from its current batch as leftovers.

Counting, summing, draining, and timing

effect function summarize() {
  const source = Stream.make(6, 10, 14)
  return {
    count: try Stream.run(source, Sink.count), // 3
    sum: try Stream.run(source, Sink.sum),     // 30
    duration: try Stream.run(source, Sink.timed)
  }
}
 
effect function drainObserved() {
  const source = Stream.tap(Stream.make("ready", "done"), (s) => Console.log(s))
  try Stream.run(source, Sink.drain)
}
// Run in an effect function:
//   const summary = try summarize()
//   {
//     const jsonValue = [summary.count, summary.sum, Duration.isDuration(summary.duration)]
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
//   try drainObserved()
// Output: [3,30,true]
// Output: ready
// Output: done

count, sum, drain, and timed all consume to stream end. drain discards values while still driving upstream effects; timed drains and returns the elapsed Duration. To measure another sink without losing its output, wrap it in Sink.withDuration(sink) to get [result, duration]. Note that each field in summarize runs source independently.

Per-element work

const print = Sink.forEach(effect (line: string) => {
  try Console.log(`record: ${line}`)
  try sleep("10 millis")
})
 
effect function writeRecords() {
  try Stream.run(Stream.make("created", "approved"), print)
}
// Run in an effect function: try writeRecords()
// Output: record: created
// Output: record: approved

Sink.forEach runs an Effect sequentially for every element and returns void, propagating the callback's failures (E) and services (R) to the sink. Use forEachWhile to stop early when the callback returns false, or forEachArray to process whole internal chunks at once.

Successful and failed sinks

error Rejected
 
effect function immediateResult() {
  return try Stream.run(Stream.make(40, 50), Sink.succeed("already complete"))
}
 
effect function rejectInput() {
  return try Stream.run(Stream.make(40, 50), Sink.fail(new Rejected()))
}
// never!Rejected
// Run in an effect function:
//   try Console.log(try immediateResult())
//   const tag = rejectInput() catch (error) => match (error) { when Rejected: error._tag; }
//   try Console.log(tag)
// Output: already complete
// Output: Rejected

Sink.succeed, Sink.fail, and Sink.fromEffect complete without pulling any elements from the stream. Sink.fail settles only when executed by Stream.run, never at construction.

Collecting by size or condition

effect function collectSamples() {
  const source = Stream.make(8, 5, -1, 13)
  return {
    all: try Stream.run(source, Sink.collect<number>()),
    firstTwo: try Stream.run(source, Sink.take<number>(2)),
    positivePrefix: try Stream.run(source, Sink.takeWhile((n: number) => n > 0))
  }
}
// all: [8, 5, -1, 13], firstTwo: [8, 5], positivePrefix: [8, 5]
// Run in an effect function:
//   {
//     const jsonValue = try collectSamples()
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
// Output: {"all":[8,5,-1,13],"firstTwo":[8,5],"positivePrefix":[8,5]}

Sink.collect gathers all elements into an array. takeWhile halts at the first element failing the predicate—leaving that element in the batch leftovers rather than skipping it—while takeUntil includes the matching element before stopping. Effectful predicates use takeWhileEffect and takeUntilEffect.

Uniqueness and key limits

const unique = Sink.reduce(() => new Set<string>(), (set, value: string) => set.add(value))
const threeUnique = Sink.reduceWhile(
  () => new Set<string>(),
  (set) => set.size < 3,
  (set, value: string) => set.add(value)
)
 
effect function collectUnique() {
  return try Stream.run(Stream.make("oak", "oak", "ash", "elm", "pine"), threeUnique)
}
// Set containing "oak", "ash", "elm".
// Run in an effect function:
//   {
//     const jsonValue = Array.from(try collectUnique())
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
// Output: ["oak","ash","elm"]

Because reduceWhile invokes () => new Set<string>() per consumption, mutating the accumulator inside the reducer is safe and isolated to one run. Duplicate values do not grow set.size, so threeUnique stops only once three distinct strings are seen.

type Reading = { station: string; count: number }
 
function addReading(totals: Map<string, number>, reading: Reading): Map<string, number> {
  totals.set(reading.station, (totals.get(reading.station) ?? 0) + reading.count)
  return totals
}
 
const allStations = Sink.reduce(() => new Map<string, number>(), (map, reading: Reading) => addReading(map, reading))
const twoStations = Sink.reduceWhile(
  () => new Map<string, number>(),
  (map) => map.size < 2,
  (map, reading: Reading) => addReading(map, reading)
)
 
effect function summarizeStations() {
  return try Stream.run(Stream.make(
    { station: "hill", count: 4 },
    { station: "hill", count: 3 },
    { station: "lake", count: 8 },
    { station: "hill", count: 9 }
  ), twoStations)
}
// Map with "hill" -> 7 and "lake" -> 8.
// Run in an effect function:
//   {
//     const jsonValue = Array.from(try summarizeStations())
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
// Output: [["hill",7],["lake",8]]

twoStations stops as soon as map.size reaches 2—leaving the trailing { station: "hill", count: 9 } unread. reduceWhile caps the consumed prefix rather than draining the entire stream while ignoring new keys.

Folding with termination and count limits

const total = Sink.reduce(() => 0, (sum, n: number) => sum + n)
const budget = Sink.fold(
  () => 0,
  (sum) => sum < 20,
  effect (sum, n: number) => {
    try log(`adding ${n}`)
    return sum + n
  }
)
const firstThree = Sink.foldUntil(() => 0, 3, effect (sum, n: number) => sum + n)
 
effect function foldSamples() {
  const source = Stream.make(7, 9, 12, 15)
  return {
    all: try Stream.run(source, total),       // 43
    budget: try Stream.run(source, budget),   // 28
    first: try Stream.run(source, firstThree) // 28
  }
}
// Run in an effect function:
//   {
//     const jsonValue = try Effect.provide(foldSamples(), Logger.layer([Logger.withConsoleLog(Logger.make(({ message }) => (message as unknown[])[0]))]))
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
// Output: adding 7
// Output: adding 9
// Output: adding 12
// Output: {"all":43,"budget":28,"first":28}

reduce runs a pure reducer to completion (reduceEffect adds Effects). fold runs an effectful step and checks its continuation predicate after incorporating each element—so 12, which pushes sum from 16 to 28, is included before stopping. foldUntil caps the number of consumed elements.

Folding by weight

type Packet = { bytes: number }
type Batch = { packets: ReadonlyArray<Packet>; bytes: number }
 
const weighted = Sink.fold<Batch, Packet>(
  () => ({ packets: [], bytes: 0 }),
  (batch) => batch.bytes < 100,
  effect (batch, packet) => ({
    packets: [...batch.packets, packet],
    bytes: batch.bytes + packet.bytes
  })
)
const packets = Sink.map(weighted, (batch) => batch.packets)
 
effect function firstBatch() {
  return try Stream.run(Stream.make({ bytes: 60 }, { bytes: 55 }, { bytes: 10 }), packets)
}
// Returns the 60-byte and 55-byte packets.
// Run in an effect function:
//   {
//     const jsonValue = try firstBatch()
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
// Output: [{"bytes":60},{"bytes":55}]

Because fold tests (batch) => batch.bytes < 100 after adding each packet, the batch that crosses 100 bytes includes the crossing packet (115 bytes total)—this is threshold batching, not strict bin-packing. Pass packets to Stream.transduce(source, packets) to emit successive weighted batches while feeding each run's leftovers into the next; filter out empty trailing batches if input can end right on a boundary.


The matching Effect page: effect.website/docs/v4/sink/creating