Created
September 15, 2020 19:02
-
-
Save stevestreza/cad01924a79564fe972eca6606764059 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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