Made the "fetch()" function for the FeedListViewController view controller in the Feed framework to use Swift concurrency.

This commit is contained in:
Javier Cicchelli 2024-03-22 15:15:16 +01:00
parent a1abe1f4ae
commit 8eec6f5666
2 changed files with 40 additions and 42 deletions

View File

@ -61,49 +61,47 @@ extension FeedListViewController {
} }
// MARK: Functions // MARK: Functions
func fetch() { func fetch() async {
Task { isFilterEnabled = false
isFilterEnabled = false isLoading = items.isEmpty
isLoading = items.isEmpty
do { do {
let output = try await iTunesService.getReviews(.init( let output = try await iTunesService.getReviews(.init(
appID: configuration.appID, appID: configuration.appID,
countryCode: configuration.countryCode countryCode: configuration.countryCode
)) ))
reviewsAll = output.reviews.map(Review.init) reviewsAll = output.reviews.map(Review.init)
reviewsFiltered = FilterOption.allCases reviewsFiltered = FilterOption.allCases
.reduce(into: FilteredReviews()) { partialResult, option in .reduce(into: FilteredReviews()) { partialResult, option in
partialResult[option] = reviewsAll.filter { $0.rating.stars == option.rawValue } partialResult[option] = reviewsAll.filter { $0.rating.stars == option.rawValue }
} }
reviewsTopWords = reviewsFiltered reviewsTopWords = reviewsFiltered
.mapValues { reviews in .mapValues { reviews in
reviews.map(\.comment) reviews.map(\.comment)
.compactMap { try? filterWords($0) } .compactMap { try? filterWords($0) }
} }
.mapValues { .mapValues {
topWords($0).map(TopWord.init) topWords($0).map(TopWord.init)
} }
items = filter == .all items = filter == .all
? reviewsAll ? reviewsAll
: reviewsFiltered[filter] ?? [] : reviewsFiltered[filter] ?? []
words = filter == .all words = filter == .all
? [] ? []
: reviewsTopWords[filter] ?? [] : reviewsTopWords[filter] ?? []
isFilterEnabled = !items.isEmpty isFilterEnabled = !items.isEmpty
state = items.isEmpty state = items.isEmpty
? .empty ? .empty
: .populated : .populated
} catch { } catch {
items = [] items = []
state = .error state = .error
}
isLoading = false
} }
isLoading = false
} }
func filter(by option: FilterOption) { func filter(by option: FilterOption) {

View File

@ -118,7 +118,7 @@ final class FeedListViewController: UIViewController {
registerTableCells() registerTableCells()
bindViewModel() bindViewModel()
viewModel.fetch() Task { await viewModel.fetch() }
} }
} }
@ -170,7 +170,7 @@ private extension FeedListViewController {
// MARK: Actions // MARK: Actions
@objc func refresh(_ sender: AnyObject) { @objc func refresh(_ sender: AnyObject) {
self.viewModel.fetch() Task { await self.viewModel.fetch() }
} }
// MARK: Functions // MARK: Functions
@ -264,7 +264,7 @@ private extension FeedListViewController {
) )
: nil, : nil,
action: isErrorState action: isErrorState
? { self.viewModel.fetch() } ? { Task { await self.viewModel.fetch() } }
: nil : nil
) )