Created
May 31, 2021 07:39
-
-
Save alfianlosari/b3ae3805f9058f59db6323fb8a9ecd8a to your computer and use it in GitHub Desktop.
Fetch API GroupTask
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
// 1 | |
func fetchAPIGroup<D: Decodable>(urls: [URL]) async throws -> [D] { | |
// 2 | |
try await withThrowingTaskGroup(of: D.self) { (group) in | |
// 3 | |
for url in urls { | |
group.async { | |
let data = try Data(contentsOf: url) | |
let decodedData = try JSONDecoder().decode(D.self, from: data) | |
return decodedData | |
} | |
} | |
// 4 | |
var results = [D]() | |
for try await result in group { | |
results.append(result) | |
} | |
return results | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment