Skip to content

Instantly share code, notes, and snippets.

@joshuajhomann
Created May 31, 2022 23:45
Show Gist options
  • Save joshuajhomann/7bc461c8d41ecbaf6644493f8cd3803d to your computer and use it in GitHub Desktop.
Save joshuajhomann/7bc461c8d41ecbaf6644493f8cd3803d to your computer and use it in GitHub Desktop.
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