From 600fca4fdc7df421b5e45e6ddc47f122c9e7b401 Mon Sep 17 00:00:00 2001 From: Laurent Date: Thu, 1 May 2025 14:56:06 +0200 Subject: [PATCH] fix collection loading --- LeStorage/BaseCollection.swift | 20 ++++++++++++-------- LeStorage/SyncedCollection.swift | 2 +- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/LeStorage/BaseCollection.swift b/LeStorage/BaseCollection.swift index 8d9b398..1607e81 100644 --- a/LeStorage/BaseCollection.swift +++ b/LeStorage/BaseCollection.swift @@ -73,9 +73,8 @@ public class BaseCollection: SomeCollection, CollectionHolder { self.limit = limit if synchronousLoading { - self.loadFromFile() Task { - await self.setAsLoaded() + await self.loadFromFile() } } else { Task(priority: .high) { @@ -109,23 +108,25 @@ public class BaseCollection: SomeCollection, CollectionHolder { /// Migrates if necessary and asynchronously decodes the json file func load() async { if !self.inMemory { - self.loadFromFile() + await self.loadFromFile() } else { - await self.setAsLoaded() + await MainActor.run { + self.setAsLoaded() + } } } /// Starts the JSON file decoding synchronously or asynchronously - func loadFromFile() { + func loadFromFile() async { do { - try self._decodeJSONFile() + try await self._decodeJSONFile() } catch { Logger.error(error) } } /// Decodes the json file into the items array - fileprivate func _decodeJSONFile() throws { + fileprivate func _decodeJSONFile() async throws { let fileURL = try self.store.fileURL(type: T.self) @@ -134,7 +135,10 @@ public class BaseCollection: SomeCollection, CollectionHolder { let decoded: [T] = try jsonString.decodeArray() ?? [] self.setItems(decoded) } - + await MainActor.run { + self.setAsLoaded() + } + } /// Sets the collection as loaded diff --git a/LeStorage/SyncedCollection.swift b/LeStorage/SyncedCollection.swift index dfcb2b3..72f4c68 100644 --- a/LeStorage/SyncedCollection.swift +++ b/LeStorage/SyncedCollection.swift @@ -25,7 +25,7 @@ public class SyncedCollection: BaseCollection, SomeSynced if self.inMemory { try await self.loadDataFromServerIfAllowed() } else { - self.loadFromFile() + await self.loadFromFile() } } catch { Logger.error(error)