From 28b91ed8c8f328ac80bebab0ce8333357b589d6f Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Sun, 22 Jan 2023 12:54:07 -0800 Subject: [PATCH] Copy fetchArticlesAsync callback fix from ios-release. --- Account/Sources/Account/AccountManager.swift | 69 ++++++++++---------- 1 file changed, 34 insertions(+), 35 deletions(-) diff --git a/Account/Sources/Account/AccountManager.swift b/Account/Sources/Account/AccountManager.swift index b5f969ca8..d589c9b23 100644 --- a/Account/Sources/Account/AccountManager.swift +++ b/Account/Sources/Account/AccountManager.swift @@ -365,45 +365,44 @@ public final class AccountManager: UnreadCountProvider { } public func fetchArticlesAsync(_ fetchType: FetchType, _ completion: @escaping ArticleSetResultBlock) { - precondition(Thread.isMainThread) - - var allFetchedArticles = Set
() - let numberOfAccounts = activeAccounts.count - var accountsReporting = 0 - var didCallCompletionBlock = false - var databaseFetchDidFail = false + precondition(Thread.isMainThread) - func callCompletion(_ result: ArticleSetResult) { - guard !didCallCompletionBlock else { - return - } - completion(result) - didCallCompletionBlock = true + guard activeAccounts.count > 0 else { + completion(.success(Set
())) + return } - guard numberOfAccounts > 0 else { - callCompletion(.success(allFetchedArticles)) - return - } - - for account in activeAccounts { - account.fetchArticlesAsync(fetchType) { (articleSetResult) in + var allFetchedArticles = Set
() + var databaseError: DatabaseError? + let dispatchGroup = DispatchGroup() + + for account in activeAccounts { + + dispatchGroup.enter() + + account.fetchArticlesAsync(fetchType) { (articleSetResult) in precondition(Thread.isMainThread) - accountsReporting += 1 - - switch articleSetResult { - case .success(let articles): - allFetchedArticles.formUnion(articles) - if accountsReporting == numberOfAccounts && !databaseFetchDidFail { - callCompletion(.success(allFetchedArticles)) - } - case .failure(let databaseError): - databaseFetchDidFail = true - callCompletion(.failure(databaseError)) - } - } - } - } + + switch articleSetResult { + case .success(let articles): + allFetchedArticles.formUnion(articles) + case .failure(let error): + databaseError = error + } + + dispatchGroup.leave() + } + } + + dispatchGroup.notify(queue: .main) { + if let databaseError { + completion(.failure(databaseError)) + } + else { + completion(.success(allFetchedArticles)) + } + } + } // MARK: - Caches