Change to a different debounce strategy and don't write widget data while in the background. #3567

This commit is contained in:
Maurice Parker 2022-10-08 17:10:40 -05:00
parent 66c7070bbd
commit 05561d9c1f
2 changed files with 17 additions and 20 deletions

View File

@ -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!)
}
}

View File

@ -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 {