Last active
January 3, 2022 23:52
-
-
Save jamesrochabrun/bade5d114b23c75fab1adbecb6a3dd24 to your computer and use it in GitHub Desktop.
Using Group tasks to synchronize networking calls.
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
// 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