Last active
June 5, 2024 15:45
-
-
Save robertmryan/9f84590ab5ce4575aa674ccfb0b2f0f4 to your computer and use it in GitHub Desktop.
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
| 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 } | |
| } | |
| } | |
| } |
Author
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
Note, returning an array of
Imageand discarding the underlyingListItem(with a bunch of interesting properties) is a curious pattern. You probably would want to return both theListItemand its associatedImage.Also, note that this pattern of retrieving all the
Imageis a bit of an antipattern. You generally want to fetch the image as needed. E.g., if there were 1000ListItem, but you can only see 10 at any point in time, do you really want this toawaitthe retrieval of all of the images? But there is not enough here to get specific on the solution, as we’d need info aboutListItem, whether it isIdentifiableor not, etc. But I just wanted to acknowledge the issues.