Skip to content

Instantly share code, notes, and snippets.

@cobbal
Created January 21, 2025 19:10
Show Gist options
  • Save cobbal/bbf69018506a6ec89ddc4e52c5a25ec9 to your computer and use it in GitHub Desktop.
Save cobbal/bbf69018506a6ec89ddc4e52c5a25ec9 to your computer and use it in GitHub Desktop.
public struct SwiftConcurrencyPublisher<Output: Sendable, Failure: Sendable & Error> : Publisher {
private let subject: Publishers.HandleEvents<PassthroughSubject<Output, Failure>>
public init(body: @Sendable @escaping () async -> Result<Output, Failure>) {
let subject = PassthroughSubject<Output, Failure>()
let task = Task {
switch await body() {
case .success(let success):
subject.send(success)
subject.send(completion: .finished)
case .failure(let failure):
subject.send(completion: .failure(failure))
}
}
self.subject = subject.handleEvents(receiveCancel: { task.cancel() })
}
public func receive<S>(subscriber: S) where S : Subscriber, Failure == S.Failure, Output == S.Input {
subject.receive(subscriber: subscriber)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment