Last active
January 22, 2020 20:47
-
-
Save Plnda/09ccb16fc1414208c0bec24e6d93dd16 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 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