MCPcopy Create free account
hub / github.com/Effect-TS/effect / fromAsyncIterable

Function fromAsyncIterable

packages/effect/src/Channel.ts:2004–2036  ·  view source on GitHub ↗
(
  iterable: AsyncIterable<A, D>,
  onError: (error: unknown) => E
)

Source from the content-addressed store, hash-verified

2002 * @since 4.0.0
2003 */
2004export const fromAsyncIterable = <A, D, E>(
2005 iterable: AsyncIterable<A, D>,
2006 onError: (error: unknown) => E
2007): Channel<A, E, D> =>
2008 fromTransform(Effect.fnUntraced(function*(_, scope) {
2009 const iter = iterable[Symbol.asyncIterator]()
2010 let pulling = false
2011 if (iter.return) {
2012 // `return()` may not settle until a pending `next()` does, so only
2013 // await it when the iterator is idle.
2014 yield* Scope.addFinalizer(
2015 scope,
2016 Effect.suspend(() =>
2017 pulling
2018 ? Effect.sync(() => void iter.return!().catch(constVoid))
2019 : Effect.promise(() => iter.return!())
2020 )
2021 )
2022 }
2023 return Effect.flatMap(
2024 Effect.tryPromise({
2025 try: () => {
2026 const promise = iter.next()
2027 pulling = true
2028 return promise.finally(() => {
2029 pulling = false
2030 })
2031 },
2032 catch: onError
2033 }),
2034 (result) => result.done ? Cause.done(result.value) : Effect.succeed(result.value)
2035 )
2036 }))
2037
2038/**
2039 * Creates a channel from an `AsyncIterable`, emitting each yielded value as a

Callers 1

fromAsyncIterableArrayFunction · 0.70

Calls 6

addFinalizerMethod · 0.80
fromTransformFunction · 0.70
nextMethod · 0.65
syncMethod · 0.45
doneMethod · 0.45
succeedMethod · 0.45

Tested by

no test coverage detected