Hyperlinkv0.8.0-beta.28

Stream

Stream.fromReadableStreamconsteffect/Stream.ts:1406
<A, E>(options: {
  readonly evaluate: LazyArg<ReadableStream<A>>
  readonly onError: (error: unknown) => E
  readonly releaseLockOnEnd?: boolean | undefined
}): Stream<A, E>

Creates a stream from a lazily supplied Web ReadableStream.

Details

The stream reads from a ReadableStreamDefaultReader, maps read failures with onError, and closes the reader when the stream finalizes. By default the reader is canceled; set releaseLockOnEnd to release the lock instead.

Example (Creating a stream from a ReadableStream)

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

class StreamError extends Data.TaggedError("StreamError")<{ readonly cause: unknown }> {}

const readableStream = new ReadableStream({
  start(controller) {
    controller.enqueue(1)
    controller.enqueue(2)
    controller.enqueue(3)
    controller.close()
  }
})

const program = Effect.gen(function*() {
  const stream = Stream.fromReadableStream({
    evaluate: () => readableStream,
    onError: (cause) => new StreamError({ cause })
  })
  const values = yield* Stream.runCollect(stream)
  yield* Console.log(values)
})

Effect.runPromise(program)
// Output: [ 1, 2, 3 ]
constructors
Source effect/Stream.ts:140623 lines
export const fromReadableStream = <A, E>(
  options: {
    readonly evaluate: LazyArg<ReadableStream<A>>
    readonly onError: (error: unknown) => E
    readonly releaseLockOnEnd?: boolean | undefined
  }
): Stream<A, E> =>
  fromChannel(Channel.fromTransform(Effect.fnUntraced(function*(_, scope) {
    const reader = options.evaluate().getReader()
    yield* Scope.addFinalizer(
      scope,
      options.releaseLockOnEnd
        ? Effect.sync(() => reader.releaseLock())
        : Effect.promise(() => reader.cancel().catch(constVoid))
    )
    return Effect.flatMap(
      Effect.tryPromise({
        try: () => reader.read(),
        catch: (reason) => options.onError(reason)
      }),
      ({ done, value }) => done ? Cause.done() : Effect.succeed(Arr.of(value))
    )
  })))