From 56360ae821ea274d0a6e90f8fff6c1870a1bf595 Mon Sep 17 00:00:00 2001 From: "Thai D. V" <46838577+thai-d-v@users.noreply.github.com> Date: Sun, 3 Dec 2023 18:43:15 +0700 Subject: [PATCH] fix: make `windowWidth` and `windowHeight` of `SceneDelegate` observable (#1693) --- .../Sources/DesignSystem/SceneDelegate.swift | 45 +++++++++++++++---- 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/Packages/DesignSystem/Sources/DesignSystem/SceneDelegate.swift b/Packages/DesignSystem/Sources/DesignSystem/SceneDelegate.swift index c93ba21d..61419be5 100644 --- a/Packages/DesignSystem/Sources/DesignSystem/SceneDelegate.swift +++ b/Packages/DesignSystem/Sources/DesignSystem/SceneDelegate.swift @@ -1,16 +1,11 @@ import Combine import UIKit -@Observable public class SceneDelegate: NSObject, UIWindowSceneDelegate { +@Observable +public class SceneDelegate: NSObject, UIWindowSceneDelegate, Sendable { public var window: UIWindow? - - public var windowWidth: CGFloat { - window?.bounds.size.width ?? UIScreen.main.bounds.size.width - } - - public var windowHeight: CGFloat { - window?.bounds.size.height ?? UIScreen.main.bounds.size.height - } + public private(set) var windowWidth: CGFloat = UIScreen.main.bounds.size.width + public private(set) var windowHeight: CGFloat = UIScreen.main.bounds.size.height public func scene(_ scene: UIScene, willConnectTo _: UISceneSession, @@ -26,4 +21,36 @@ import UIKit } #endif } + + public override init() { + super.init() + self.windowWidth = self.window?.bounds.size.width ?? UIScreen.main.bounds.size.width + self.windowHeight = self.window?.bounds.size.height ?? UIScreen.main.bounds.size.height + Self.observedSceneDelegate.insert(self) + _ = Self.observer // just for activating the lazy static property + } + + deinit { + Task { @MainActor in + Self.observedSceneDelegate.remove(self) + } + } + + private static var observedSceneDelegate: Set = [] + private static let observer = Task { + while true { + try? await Task.sleep(for: .seconds(0.1)) + for delegate in observedSceneDelegate { + let newWidth = delegate.window?.bounds.size.width ?? UIScreen.main.bounds.size.width + if delegate.windowWidth != newWidth { + delegate.windowWidth = newWidth + } + + let newHeight = delegate.window?.bounds.size.height ?? UIScreen.main.bounds.size.height + if delegate.windowHeight != newHeight { + delegate.windowHeight = newHeight + } + } + } + } }