Created
August 7, 2021 18:41
-
-
Save bolivarbryan/2f8ba79d94c32e8f7c74eb2a81ebfa67 to your computer and use it in GitHub Desktop.
Generic Fetch Request With Combine
This file contains hidden or 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
/* | |
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