Skip to content

Commit

Permalink
Convert background worker queue to continuations
Browse files Browse the repository at this point in the history
  • Loading branch information
armandsLa committed Mar 29, 2024
1 parent 365f8f9 commit 25ca097
Showing 1 changed file with 16 additions and 15 deletions.
31 changes: 16 additions & 15 deletions ios/Classes/HomeWidgetBackgroundWorker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Void, Never>] = []

private static var registerPlugins: FlutterPluginRegistrantCallback?

Expand All @@ -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) {
Expand Down Expand Up @@ -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:
Expand Down

0 comments on commit 25ca097

Please sign in to comment.