Skip to content

Instantly share code, notes, and snippets.

@manmal
Created July 6, 2022 16:57
Show Gist options
  • Save manmal/e1161331357ff50a7c1129a2dd6f926d to your computer and use it in GitHub Desktop.
Save manmal/e1161331357ff50a7c1129a2dd6f926d to your computer and use it in GitHub Desktop.
AsyncSequence.eraseToAsyncStream()
import Foundation
// Props to @pteasima and @MichalKleinJr:
// https://twitter.com/pteasima/status/1544723987606929408?s=21&t=JL1oIuL87Ms_VPBQBZQ7Rg
public extension AsyncSequence {
func eraseToAsyncStream() -> AsyncStream<Element> {
return AsyncStream { continuation in
let task = Task {
do {
for try await value in self {
try Task.checkCancellation()
continuation.yield(value)
}
continuation.finish()
} catch {
continuation.finish()
}
}
continuation.onTermination = { _ in task.cancel() }
}
}
func eraseToAsyncThrowingStream() -> AsyncThrowingStream<Element, Error> {
return AsyncThrowingStream { continuation in
let task = Task {
do {
for try await value in self {
try Task.checkCancellation()
continuation.yield(value)
}
continuation.finish()
} catch {
continuation.finish(throwing: error)
}
}
continuation.onTermination = { _ in task.cancel() }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment