Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Last active June 5, 2024 15:45
Show Gist options
  • Select an option

  • Save robertmryan/9f84590ab5ce4575aa674ccfb0b2f0f4 to your computer and use it in GitHub Desktop.

Select an option

Save robertmryan/9f84590ab5ce4575aa674ccfb0b2f0f4 to your computer and use it in GitHub Desktop.
extension ImageDownloader {
// if you don't care about the order
func downloadInRandomOrder() async -> [Image] {
await withTaskGroup(of: Image.self) { group in
let items = await fetchList()
for item in items {
group.addTask { await self.fetch(imageName: item.imageName) }
}
return await group.reduce(into: []) { $0.append($1) }
}
}
// if you want them in order
func downloadInOrder() async -> [Image] {
await withTaskGroup(of: (Int, Image).self) { group in
let items = await fetchList()
for (index, item) in items.enumerated() {
group.addTask { await (index, self.fetch(imageName: item.imageName)) }
}
let dictionary = await group.reduce(into: [:]) { $0[$1.0] = $1.1 }
return (0..<items.count).compactMap { dictionary[$0] }
}
}
// Order independent result
func downloadInOrder() async -> [String: Image] {
await withTaskGroup(of: (String, Image).self) { group in
let items = await fetchList()
for item in items {
group.addTask { await (item.imageName, self.fetch(imageName: item.imageName)) }
}
return await group.reduce(into: [:]) { $0[$1.0] = $1.1 }
}
}
}
@robertmryan

robertmryan commented Mar 2, 2024

Copy link
Copy Markdown
Author

Note, returning an array of Image and discarding the underlying ListItem (with a bunch of interesting properties) is a curious pattern. You probably would want to return both the ListItem and its associated Image.

Also, note that this pattern of retrieving all the Image is a bit of an antipattern. You generally want to fetch the image as needed. E.g., if there were 1000 ListItem, but you can only see 10 at any point in time, do you really want this to await the retrieval of all of the images? But there is not enough here to get specific on the solution, as we’d need info about ListItem, whether it is Identifiable or not, etc. But I just wanted to acknowledge the issues.

@robertmryan

robertmryan commented Mar 2, 2024

Copy link
Copy Markdown
Author

I noticed that the OP’s code did not assume that the imageName must be a URL, so I removed it from the above. Perhaps the OP’s fetch is building a URL from the imageName

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment