Skip to content

Instantly share code, notes, and snippets.

@davbeck
Created July 31, 2020 03:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davbeck/f4cdd3c6ddc33cbb59a05e01c593d60f to your computer and use it in GitHub Desktop.
Save davbeck/f4cdd3c6ddc33cbb59a05e01c593d60f to your computer and use it in GitHub Desktop.
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