Hyperlinkv0.8.0-beta.28

Stream

Stream.peelconsteffect/Stream.ts:4772
<A2, A, E2, R2>(sink: Sink.Sink<A2, A, A, E2, R2>): <E, R>(
  self: Stream<A, E, R>
) => Effect.Effect<
  [A2, Stream<A, E, never>],
  E2 | E,
  Scope.Scope | R2 | R
>
<A, E, R, A2, E2, R2>(
  self: Stream<A, E, R>,
  sink: Sink.Sink<A2, A, A, E2, R2>
): Effect.Effect<[A2, Stream<A, E, never>], E | E2, Scope.Scope | R | R2>

Runs a sink to peel off enough elements to produce a value and returns that value with the remaining stream in a scope.

Details

The returned stream is only valid within the scope.

Example (Peeling a stream with a sink)

import { Console, Effect, Sink, Stream } from "effect"

const stream = Stream.fromArrays([1, 2, 3], [4, 5, 6])
const sink = Sink.take<number>(3)

const program = Effect.scoped(
  Effect.gen(function*() {
    const [peeled, rest] = yield* Stream.peel(stream, sink)
    const remaining = yield* Stream.runCollect(rest)
    yield* Console.log([peeled, remaining])
  })
)

Effect.runPromise(program)
// Output: [ [1, 2, 3], [4, 5, 6] ]
destructors
Source effect/Stream.ts:477232 lines
export const peel: {
  <A2, A, E2, R2>(
    sink: Sink.Sink<A2, A, A, E2, R2>
  ): <E, R>(self: Stream<A, E, R>) => Effect.Effect<[A2, Stream<A, E, never>], E2 | E, Scope.Scope | R2 | R>
  <A, E, R, A2, E2, R2>(
    self: Stream<A, E, R>,
    sink: Sink.Sink<A2, A, A, E2, R2>
  ): Effect.Effect<[A2, Stream<A, E, never>], E | E2, Scope.Scope | R | R2>
} = dual(
  2,
  Effect.fnUntraced(function*<A, E, R, A2, E2, R2>(
    self: Stream<A, E, R>,
    sink: Sink.Sink<A2, A, A, E2, R2>
  ): Effect.fn.Return<[A2, Stream<A, E, never>], E | E2, Scope.Scope | R | R2> {
    let cause: Cause.Cause<E | Cause.Done<void>> | undefined = undefined
    const originalPull = yield* Channel.toPull(self.channel)
    const pull: Pull.Pull<
      Arr.NonEmptyReadonlyArray<A>,
      E
    > = Effect.catchCause(originalPull, (cause_) => {
      cause = cause_
      return Effect.failCause(cause_)
    })

    let stream = fromPull(Effect.succeed(pull)) as Stream<A, E>
    const leftover = yield* run(stream, sink)
    if (cause) return [leftover, empty]

    stream = fromPull(Effect.succeed(originalPull))
    return [leftover, stream]
  })
)