Skip to content

Instantly share code, notes, and snippets.

@Plnda
Last active January 22, 2020 20:47
Show Gist options
  • Save Plnda/09ccb16fc1414208c0bec24e6d93dd16 to your computer and use it in GitHub Desktop.
Save Plnda/09ccb16fc1414208c0bec24e6d93dd16 to your computer and use it in GitHub Desktop.
import Foundation
import Combine
protocol NetworkViewModel: ObservableObject {
associatedtype NetworkResource: Decodable
var objectWillChange: ObservableObjectPublisher { get }
var resource: Resource<NetworkResource> { get set }
var network: Network { get set }
var route: NetworkRoute { get }
var bag: Set<AnyCancellable> { get set }
func onAppear()
}
extension NetworkViewModel {
func fetch(route: NetworkRoute) {
(network.fetch(route: route) as AnyPublisher<NetworkResource, Error>)
.receive(on: RunLoop.main)
.sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
self.resource = .error(error)
self.objectWillChange.send()
default:
break
}
}, receiveValue: { decodable in
self.resource = .success(decodable)
self.objectWillChange.send()
})
.store(in: &bag)
}
func onAppear() {
fetch(route: route)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment