| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- import Foundation
- import Combine
- @MainActor final class LaunchCoordinator: ObservableObject {
- @Published private(set) var isLaunching = true
- private(set) var didTimeout = false
- private var started = false
- private var operation: Task<Void, Never>?
- private var deadline: Task<Void, Never>?
- private var completion: CheckedContinuation<Void, Never>?
- func start(platform: PlatformBootstrap, language: AppLanguage,
- timeoutNanoseconds: UInt64 = 5_000_000_000,
- isReady: @escaping @MainActor () -> Bool = { true }) async {
- guard !started else { return }
- started = true
- await withTaskCancellationHandler {
- await withCheckedContinuation { continuation in
- completion = continuation
- deadline = Task { [weak self] in
- do { try await Task.sleep(nanoseconds: timeoutNanoseconds) } catch { return }
- self?.finish(timedOut: true)
- }
- operation = Task { [weak self] in
- while !isReady() {
- do { try await Task.sleep(nanoseconds: 25_000_000) } catch { return }
- }
- guard !Task.isCancelled else { return }
- await platform.activate(language: language, requestAuthorization: false)
- guard !Task.isCancelled else { return }
- self?.finish(timedOut: false)
- }
- }
- } onCancel: {
- Task { @MainActor [weak self] in self?.finish(timedOut: false, cancelOperation: true) }
- }
- }
- private func finish(timedOut: Bool, cancelOperation: Bool = false) {
- guard isLaunching else { return }
- didTimeout = timedOut
- if timedOut || cancelOperation { operation?.cancel() }
- deadline?.cancel()
- operation = nil; deadline = nil
- isLaunching = false
- completion?.resume()
- completion = nil
- }
- }
|