Created
July 6, 2022 16:57
-
-
Save manmal/e1161331357ff50a7c1129a2dd6f926d to your computer and use it in GitHub Desktop.
AsyncSequence.eraseToAsyncStream()
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
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