Skip to content

Instantly share code, notes, and snippets.

@stevestreza
Created September 15, 2020 19:02
Show Gist options
  • Save stevestreza/cad01924a79564fe972eca6606764059 to your computer and use it in GitHub Desktop.
Save stevestreza/cad01924a79564fe972eca6606764059 to your computer and use it in GitHub Desktop.
import Combine
import Foundation
class ObservablePublisher<T, U: Error>: ObservableObject {
var result: Result<T, U>?
var value: T? {
if let result = self.result, case .success(let value) = result {
return value
}
else {
return nil
}
}
var error: U? {
if let result = self.result, case .failure(let error) = result {
return error
}
else {
return nil
}
}
var cancellable: AnyCancellable?
init<P: Publisher>(publisher: P) where P.Output == T, P.Failure == U {
cancellable = publisher
.receive(on: DispatchQueue.main)
.sink { (completion) in
guard case .failure(let error) = completion else {
return
}
self.result = .failure(error)
self.objectWillChange.send()
} receiveValue: { (value) in
self.result = .success(value)
self.objectWillChange.send()
}
}
}
extension Publisher {
var asObservableObject: ObservablePublisher<Output, Failure> {
ObservablePublisher(publisher: self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment