From 25ca09702b3b5cd3b5e0ef27306537e0c17d7a7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Armands=20Lazdin=CC=A7s=CC=8C?= Date: Fri, 29 Mar 2024 20:28:12 +0200 Subject: [PATCH] Convert background worker queue to continuations --- ios/Classes/HomeWidgetBackgroundWorker.swift | 31 ++++++++++---------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/ios/Classes/HomeWidgetBackgroundWorker.swift b/ios/Classes/HomeWidgetBackgroundWorker.swift index 0696685a..b40b590e 100644 --- a/ios/Classes/HomeWidgetBackgroundWorker.swift +++ b/ios/Classes/HomeWidgetBackgroundWorker.swift @@ -15,10 +15,11 @@ public struct HomeWidgetBackgroundWorker { static let dispatcherKey: String = "home_widget.internal.background.dispatcher" static let callbackKey: String = "home_widget.internal.background.callback" - static var isSetupCompleted: Bool = false static var engine: FlutterEngine? static var channel: FlutterMethodChannel? - static var queue: [(URL?, String)] = [] + + static var isSetupCompleted: Bool = false + static var continuations: [CheckedContinuation] = [] private static var registerPlugins: FlutterPluginRegistrantCallback? @@ -30,15 +31,17 @@ public struct HomeWidgetBackgroundWorker { /// The url you provide will be used as arguments in the callback function in dart /// The AppGroup is necessary to retrieve the dart callbacks static public func run(url: URL?, appGroup: String) async { - if isSetupCompleted { - let preferences = UserDefaults.init(suiteName: appGroup) - let dispatcher = preferences?.object(forKey: dispatcherKey) as! Int64 - NSLog("Dispatcher: \(dispatcher)") - - await sendEvent(url: url, appGroup: appGroup) - } else { - queue.append((url, appGroup)) + if isSetupCompleted == false { + await withCheckedContinuation { continuation in + continuations.append(continuation) + } } + + let preferences = UserDefaults.init(suiteName: appGroup) + let dispatcher = preferences?.object(forKey: dispatcherKey) as! Int64 + NSLog("Dispatcher: \(dispatcher)") + + await sendEvent(url: url, appGroup: appGroup) } static func setupEngine(dispatcher: Int64) { @@ -69,11 +72,9 @@ public struct HomeWidgetBackgroundWorker { switch call.method { case "HomeWidget.backgroundInitialized": isSetupCompleted = true - while !queue.isEmpty { - let entry = queue.removeFirst() - Task { - await sendEvent(url: entry.0, appGroup: entry.1) - } + while !continuations.isEmpty { + let continuation = continuations.removeFirst() + continuation.resume() } result(true) default: