Skip to content

Instantly share code, notes, and snippets.

@jamesrochabrun
Last active January 3, 2022 23:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesrochabrun/bade5d114b23c75fab1adbecb6a3dd24 to your computer and use it in GitHub Desktop.
Save jamesrochabrun/bade5d114b23c75fab1adbecb6a3dd24 to your computer and use it in GitHub Desktop.
Using Group tasks to synchronize networking calls.
// MARK:- Async/await Group task
// 1
@available(iOS 15, *)
func asyncGroups(
from categoryIdentifiers: [ItunesCategoryIdentifier]) {
// 2
Task.init {
// 3
var sections: [ItunesCategorySection] = []
// 4
try await withThrowingTaskGroup(of: ItunesCategorySection.self) { categorySection in
// 5
for categoryIdentifier in categoryIdentifiers {
// 6
categorySection.addTask {
let feedItemViewModels = try await self.service.clientFetchAsync(Feed<ItunesResources<FeedItem>>.self, itunes: Itunes(mediaTypePath: categoryIdentifier.mediaType)).feed?.results.map { FeedItemViewModel(model: $0) } ?? []
return ItunesCategorySection(sectionID: categoryIdentifier, cellIDs: feedItemViewModels)
}
}
// 7
for try await itunesCategorySection in categorySection {
// 8
sections.append(itunesCategorySection)
}
}
// 9
self.itunesSections = sections.sorted { $0.sectionID.rawValue < $1.sectionID.rawValue }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment