Created
July 31, 2020 03:33
-
-
Save davbeck/f4cdd3c6ddc33cbb59a05e01c593d60f 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 | |
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