Created
May 17, 2023 17:54
-
-
Save moyerr/010fa5e287ef4289a60e6c75c1fb7a5c to your computer and use it in GitHub Desktop.
A type-erased AsyncSequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct AnyAsyncSequence<Element>: AsyncSequence { | |
struct AnyAsyncIterator: AsyncIteratorProtocol { | |
private let _next: () async throws -> Element? | |
init<Base: AsyncSequence>(_ base: Base) where Base.Element == Element { | |
var baseIterator = base.makeAsyncIterator() | |
self._next = { try await baseIterator.next() } | |
} | |
func next() async throws -> Element? { | |
try await _next() | |
} | |
} | |
private let _makeAsyncIterator: () -> AnyAsyncIterator | |
init<Base: AsyncSequence>(_ base: Base) where Base.Element == Element { | |
self._makeAsyncIterator = { AnyAsyncIterator(base) } | |
} | |
func makeAsyncIterator() -> AnyAsyncIterator { | |
_makeAsyncIterator() | |
} | |
} | |
extension AsyncSequence { | |
func eraseToAnyAsyncSequence() -> AnyAsyncSequence<Element> { | |
AnyAsyncSequence(self) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment