import Foundation
#if canImport(UIKit) && !os(watchOS)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
/// Calls `onForeground` when the app returns to the foreground (iOS) or becomes
/// active (macOS), so rooms can reconnect immediately instead of waiting out a backoff.
final class AppLifecycleObserver: Sendable {
private let task: Task<Void, Never>?
init(onForeground: @escaping @Sendable () async -> Void) {
#if canImport(UIKit) && !os(watchOS)
let name = UIApplication.willEnterForegroundNotification
#elseif canImport(AppKit)
let name = NSApplication.didBecomeActiveNotification
#else
let name: Notification.Name? = nil
#endif
if let name = name as Notification.Name? {
task = Task {
for await _ in NotificationCenter.default.notifications(named: name) {
if Task.isCancelled { return }
await onForeground()
}
}
} else {
task = nil
}
}
func cancel() { task?.cancel() }
}