Skip to content

Instantly share code, notes, and snippets.

@rpassis
Forked from IanKeen/AnyPublisher+Extension.swift
Created September 1, 2021 22:23
Show Gist options
  • Save rpassis/b1eed67b2baf18a44fcfdd52cfb61681 to your computer and use it in GitHub Desktop.
Save rpassis/b1eed67b2baf18a44fcfdd52cfb61681 to your computer and use it in GitHub Desktop.
Extension to create an AnyPublisher to easily 'lift' async code into Combine
extension AnyPublisher where Failure: Error {
struct Subscriber {
fileprivate let send: (Output) -> Void
fileprivate let complete: (Subscribers.Completion<Failure>) -> Void
func send(_ value: Output) { self.send(value) }
func send(completion: Subscribers.Completion<Failure>) { self.complete(completion) }
}
init(_ closure: (Subscriber) -> AnyCancellable) {
let subject = PassthroughSubject<Output, Failure>()
let subscriber = Subscriber(
send: subject.send,
complete: subject.send(completion:)
)
let cancel = closure(subscriber)
self = subject
.handleEvents(receiveCancel: cancel.cancel)
.eraseToAnyPublisher()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment