Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import Combine
import Foundation
import SwiftUI
class ObservablePublisher<Output>: ObservableObject {
@Published var output: Output?
@Published var error: Swift.Error?
private var observer: AnyCancellable?
init() {}
init<P: Publisher>(_ publisher: P) where P.Output == Output {
self.load(publisher)
}
var isLoading: Bool {
self.output == nil && self.error == nil
}
func load<P: Publisher>(_ publisher: P) where P.Output == Output {
self.output = nil
self.error = nil
self.observer?.cancel()
self.observer = publisher
.receive(on: RunLoop.main)
.sink { completion in
switch completion {
case let .failure(error):
self.error = error
case .finished:
break
}
} receiveValue: { output in
self.output = output
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment