From 7745797974d3340d97ec5a21f05f291c38703347 Mon Sep 17 00:00:00 2001 From: Laurent Date: Thu, 16 May 2024 11:11:31 +0200 Subject: [PATCH] change loadDataFromServerIfAllowed to an async method --- LeStorage/Store.swift | 4 +++- LeStorage/StoredCollection.swift | 22 +++++++++++----------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/LeStorage/Store.swift b/LeStorage/Store.swift index f54b3b5..30dca12 100644 --- a/LeStorage/Store.swift +++ b/LeStorage/Store.swift @@ -248,7 +248,9 @@ public class Store { public func loadCollectionFromServer() { for collection in self._collections.values { - try? collection.loadDataFromServerIfAllowed() + Task { + try? await collection.loadDataFromServerIfAllowed() + } } } diff --git a/LeStorage/StoredCollection.swift b/LeStorage/StoredCollection.swift index 239edfe..afbaa30 100644 --- a/LeStorage/StoredCollection.swift +++ b/LeStorage/StoredCollection.swift @@ -18,7 +18,7 @@ protocol SomeCollection: Identifiable { func deleteById(_ id: String) throws func deleteApiCallById(_ id: String) throws func reset() - func loadDataFromServerIfAllowed() throws + func loadDataFromServerIfAllowed() async throws var synchronized: Bool { get } func hasPendingAPICalls() -> Bool } @@ -116,7 +116,9 @@ public class StoredCollection: RandomAccessCollection, SomeCollecti do { if self._inMemory { - try self.loadDataFromServerIfAllowed() + Task { + try await self.loadDataFromServerIfAllowed() + } } else { try self._loadFromFile() } @@ -171,18 +173,16 @@ public class StoredCollection: RandomAccessCollection, SomeCollecti } /// Retrieves the data from the server and loads it into the items array - public func loadDataFromServerIfAllowed() throws { + public func loadDataFromServerIfAllowed() async throws { guard self.synchronized, !(self is StoredSingleton) else { throw StoreError.unSynchronizedCollection } - Task { - do { - let items: [T] = try await self._store.getItems() - try self._addOrUpdate(contentOfs: items, shouldSync: false) - self._hasChanged = true - } catch { - Logger.error(error) - } + do { + let items: [T] = try await self._store.getItems() + try self._addOrUpdate(contentOfs: items, shouldSync: false) + self._hasChanged = true + } catch { + Logger.error(error) } }