Last active
July 24, 2023 20:34
-
-
Save BrentMifsud/007a346bf899d448779426e4a310c87f to your computer and use it in GitHub Desktop.
Convenience methods for converting any async sequence into an async stream
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
fileprivate extension AsyncStream { | |
init<Base: AsyncSequence>(from sequence: Base, file: StaticString = #filePath, line: UInt = #line) where Element == Base.Element { | |
var iterator = sequence.makeAsyncIterator() | |
// FIXME: In later swift versions, AsyncSequence protocol will likely have an associated error type. | |
// FIXME: For now, produce an assertionFailure to let developer know to use an AsyncThrowingStream instead. | |
self.init { | |
do { | |
return try await iterator.next() | |
} catch { | |
assertionFailure("warning: Base AsyncSequence threw an error. Use AsyncThrowingStream instead", file: file, line: line) | |
return nil | |
} | |
} | |
} | |
} | |
fileprivate extension AsyncThrowingStream { | |
init<Base: AsyncSequence>(from sequence: Base) where Element == Base.Element, Failure == Error { | |
var iterator = sequence.makeAsyncIterator() | |
self.init { | |
try await iterator.next() | |
} | |
} | |
} | |
extension AsyncSequence { | |
/// Type erases the `AsyncSequence` into an `AsyncStream` | |
/// - Returns: An `AsyncStream` created from the base `AsyncSequence` | |
/// | |
/// - Note: AsyncSequences do not expose their error type. | |
/// So this function is available for both throwing and non-throwing `AsyncSequences`. | |
/// It will produce an `assertionFailure` at runtime if the base sequence throws. | |
func asAsyncStream(file: StaticString = #filePath, line: UInt = #line) -> AsyncStream<Element> { | |
AsyncStream(from: self, file: file, line: line) | |
} | |
/// Type erases the `AsyncSequence` into an `AsyncThrowingStream` | |
/// - Returns: An `AsyncThrowingStream` from the base `AsyncSequence` | |
func asAsyncThrowingStream() -> AsyncThrowingStream<Element, Error> { | |
AsyncThrowingStream(from: self) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment