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

View File

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