-
-
Save joshuajhomann/7bc461c8d41ecbaf6644493f8cd3803d to your computer and use it in GitHub Desktop.
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
final class Pipe<Element> { | |
private(set) var send: (Element) -> Void = { _ in } | |
func makeStream() -> AsyncStream<Element> { | |
.init(Element.self, bufferingPolicy: .bufferingNewest(1)) { continuation in | |
send = { element in | |
continuation.yield(element) | |
} | |
} | |
} | |
} | |
final class ThrowingPipe<Element> { | |
private(set) var send: (Result<Element, Error>) -> Void = { _ in } | |
var failure: Error? | |
func makeStream() -> AsyncThrowingStream<Element, Error> { | |
.init(Element.self, bufferingPolicy: .bufferingNewest(1)) { [weak self] continuation in | |
send = { result in | |
result.mapError { someError -> Error in | |
let failure = self?.failure ?? someError | |
self?.failure = failure | |
return failure | |
} | |
guard let failure = self?.failure else { | |
continuation.yield(with: result) | |
return | |
} | |
continuation.yield(with: .failure(failure)) | |
} | |
} | |
} | |
func send(_ element: Element) { | |
send(.success(element)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment