Skip to content

Instantly share code, notes, and snippets.

@manmal
Created July 17, 2022 09:44
Show Gist options
  • Save manmal/55cb08fa94a4b6cecb27a6763f07ee8a to your computer and use it in GitHub Desktop.
Save manmal/55cb08fa94a4b6cecb27a6763f07ee8a to your computer and use it in GitHub Desktop.
AsyncPassthroughSubject - Swift Structured Concurrency
import Foundation
/// Provides a safe stream of `values`.
public struct AsyncPassthroughSubject<T> {
public let values: AsyncStream<T>
private let input: AsyncStream<T>.Continuation
private var isFinished = false
public init(
bufferingPolicy: AsyncStream<T>.Continuation.BufferingPolicy = .unbounded
) {
var input: AsyncStream<T>.Continuation!
self.values = AsyncStream<T>(bufferingPolicy: bufferingPolicy) { input = $0 }
self.input = input
}
public func send(_ value: T) {
guard !isFinished else { return }
input.yield(value)
}
public mutating func finish() {
isFinished = true
input.finish()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment