CoreDataInitializationCoordinator.swift 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /// This actor provides us with logic to handle cases when a caller
  2. /// tries to initialize a coreDataStack that is already initialized.
  3. actor CoreDataInitializationCoordinator {
  4. private var isInitialized = false
  5. private var initializationTask: Task<Void, Error>?
  6. /// Ensures that initialization only happens once and manages multiple concurrent initialization requests.
  7. /// This actor provides synchronization for the CoreDataStack initialization process.
  8. ///
  9. /// - Parameters:
  10. /// - initialization: A closure that performs the actual initialization work.
  11. /// - Throws: Any error that might occur during initialization.
  12. /// - Returns: Void once initialization is complete.
  13. func ensureInitialized(perform initialization: @escaping () async throws -> Void) async throws {
  14. // If already initialized, return immediately
  15. if isInitialized {
  16. return
  17. }
  18. // If initialization is in progress, await the existing task
  19. if let existingTask = initializationTask {
  20. try await existingTask.value
  21. return
  22. }
  23. // Start a new initialization task
  24. let newTask = Task {
  25. do {
  26. try await initialization()
  27. isInitialized = true
  28. } catch {
  29. // Clear task reference on failure
  30. initializationTask = nil
  31. throw error
  32. }
  33. // Clear task reference on success
  34. initializationTask = nil
  35. }
  36. initializationTask = newTask
  37. try await newTask.value
  38. }
  39. }