diff --git a/Shared/Widget/WidgetDataEncoder.swift b/Shared/Widget/WidgetDataEncoder.swift index 5276470f0..e5a7af530 100644 --- a/Shared/Widget/WidgetDataEncoder.swift +++ b/Shared/Widget/WidgetDataEncoder.swift @@ -25,38 +25,34 @@ public final class WidgetDataEncoder { private lazy var imageContainer = containerURL?.appendingPathComponent("widgetImages", isDirectory: true) private lazy var dataURL = containerURL?.appendingPathComponent("widget-data.json") - private let encodeWidgetDataQueue = CoalescingQueue(name: "Encode the Widget Data", interval: 5.0) + private var searchWorkItem: DispatchWorkItem? init () { if imageContainer != nil { try? FileManager.default.createDirectory(at: imageContainer!, withIntermediateDirectories: true, attributes: nil) } - if #available(iOS 14, *) { - NotificationCenter.default.addObserver(self, selector: #selector(statusesDidChange(_:)), name: .StatusesDidChange, object: nil) - } + NotificationCenter.default.addObserver(self, selector: #selector(statusesDidChange(_:)), name: .StatusesDidChange, object: nil) } - func encodeIfNecessary() { - encodeWidgetDataQueue.performCallsImmediately() + func pause() { + searchWorkItem?.cancel() + } + + func resume() { + dispatchWorkItem() } - @available(iOS 14, *) @objc func statusesDidChange(_ note: Notification) { - encodeWidgetDataQueue.add(self, #selector(performEncodeWidgetData)) + dispatchWorkItem() } - @available(iOS 14, *) - @objc private func performEncodeWidgetData() { - // We will be on the Main Thread when the encodeIfNecessary function is called. We want - // block the main thread in that case so that the widget data is encoded. If it is on - // a background Thread, it was called by the CoalescingQueue. In that case we need to - // move it to the Main Thread and want to execute it async. - if Thread.isMainThread { - encodeWidgetData() - } else { - DispatchQueue.main.async { - self.encodeWidgetData() + func dispatchWorkItem() { + if #available(iOS 14, *) { + searchWorkItem?.cancel() + searchWorkItem = DispatchWorkItem { [weak self] in + self?.encodeWidgetData() } + DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: searchWorkItem!) } } diff --git a/iOS/AppDelegate.swift b/iOS/AppDelegate.swift index 8ba3c7288..cc7ea16cc 100644 --- a/iOS/AppDelegate.swift +++ b/iOS/AppDelegate.swift @@ -175,7 +175,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD func prepareAccountsForBackground() { extensionFeedAddRequestFile.suspend() - widgetDataEncoder.encodeIfNecessary() + widgetDataEncoder.pause() syncTimer?.invalidate() scheduleBackgroundFeedRefresh() syncArticleStatus() @@ -184,6 +184,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterD func prepareAccountsForForeground() { extensionFeedAddRequestFile.resume() + widgetDataEncoder.resume() syncTimer?.update() if let lastRefresh = AppDefaults.shared.lastRefresh {