Skip to content

Instantly share code, notes, and snippets.

@bolivarbryan
Created August 7, 2021 18:41
Show Gist options
  • Save bolivarbryan/2f8ba79d94c32e8f7c74eb2a81ebfa67 to your computer and use it in GitHub Desktop.
Save bolivarbryan/2f8ba79d94c32e8f7c74eb2a81ebfa67 to your computer and use it in GitHub Desktop.
Generic Fetch Request With Combine
/*
QUICK network requests using Combine and Generics, Don't forget to import combibe
let url = URL(string: "https://www.hackingwithswift.com/samples/user-24601.json")!
fetch(url, defaultValue: User.default) {
print($0.name)
}
*/
func fetch<T: Decodable>(_ url: URL, defaultValue: T, completion: @escaping (T) -> Void) {
let decoder = JSONDecoder()
URLSession.shared
.dataTaskPublisher(for: url)
.retry(1)
.map(\.data)
.decode(type: T.self, decoder: decoder)
.replaceError(with: defaultValue)
.receive(on: DispatchQueue.main)
.sink(receiveValue: completion)
.store(in: &requests)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment