LaunchCoordinator.swift 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import Foundation
  2. import Combine
  3. @MainActor final class LaunchCoordinator: ObservableObject {
  4. @Published private(set) var isLaunching = true
  5. private(set) var didTimeout = false
  6. private var started = false
  7. private var operation: Task<Void, Never>?
  8. private var deadline: Task<Void, Never>?
  9. private var completion: CheckedContinuation<Void, Never>?
  10. func start(platform: PlatformBootstrap, language: AppLanguage,
  11. timeoutNanoseconds: UInt64 = 5_000_000_000,
  12. isReady: @escaping @MainActor () -> Bool = { true }) async {
  13. guard !started else { return }
  14. started = true
  15. await withTaskCancellationHandler {
  16. await withCheckedContinuation { continuation in
  17. completion = continuation
  18. deadline = Task { [weak self] in
  19. do { try await Task.sleep(nanoseconds: timeoutNanoseconds) } catch { return }
  20. self?.finish(timedOut: true)
  21. }
  22. operation = Task { [weak self] in
  23. while !isReady() {
  24. do { try await Task.sleep(nanoseconds: 25_000_000) } catch { return }
  25. }
  26. guard !Task.isCancelled else { return }
  27. await platform.activate(language: language, requestAuthorization: false)
  28. guard !Task.isCancelled else { return }
  29. self?.finish(timedOut: false)
  30. }
  31. }
  32. } onCancel: {
  33. Task { @MainActor [weak self] in self?.finish(timedOut: false, cancelOperation: true) }
  34. }
  35. }
  36. private func finish(timedOut: Bool, cancelOperation: Bool = false) {
  37. guard isLaunching else { return }
  38. didTimeout = timedOut
  39. if timedOut || cancelOperation { operation?.cancel() }
  40. deadline?.cancel()
  41. operation = nil; deadline = nil
  42. isLaunching = false
  43. completion?.resume()
  44. completion = nil
  45. }
  46. }