Generalization Shines
Look at this beauty.
/// Send URL request and publish results.
func movieDataTaskPublisher<T: Decodable>(urlRequest: URLRequest, type: T.Type)
-> AnyPublisher<T, Error> {
return URLSession.shared
.dataTaskPublisher(for: urlRequest)
.map {$0.data}
.decode(type: T.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
/// Send a request and publish a stream of Decodable.
func fetch<T: Decodable>(endPoint: String, userDefaults: UserDefaults?)
-> AnyPublisher<T, Error> {
do {
let urlRequest = try prepareRequestFor(endPoint: endPoint,
userDefaults: userDefaults)
return movieDataTaskPublisher(urlRequest: urlRequest, type: T.self)
} catch MovieServiceError.misconfiguration {
return Empty<T, Error>().eraseToAnyPublisher()
} catch {
return Empty<T, Error>().eraseToAnyPublisher()
}
}