Parent background context to PSC to prevent hangs when updating widget

This commit is contained in:
Shadowfacts 2022-09-09 23:51:41 -04:00
parent 2380eeee4a
commit c12b9ae879
2 changed files with 6 additions and 2 deletions

View File

@ -19,8 +19,9 @@ public class PersistentContainer: NSPersistentContainer, @unchecked Sendable {
public private(set) lazy var backgroundContext: NSManagedObjectContext = {
let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
// todo: should the background context really be parented to the view context, or should they both be direct children of the PSC?
context.parent = self.viewContext
// the background context needs to be parented directly to the PSC
// if it's parented to the viewContext, it blocks the viewContext (and potentially the main thread) when it needs to look things up
context.persistentStoreCoordinator = self.persistentStoreCoordinator
return context
}()

View File

@ -11,6 +11,7 @@ import Persistence
import OSLog
private let logger = Logger(subsystem: "net.shadowfacts.Reader", category: "WidgetHelper")
private let signposter = OSSignposter(logger: logger)
struct WidgetHelper {
private init() {}
@ -26,7 +27,9 @@ struct WidgetHelper {
req.sortDescriptors = [NSSortDescriptor(key: "published", ascending: false)]
req.fetchLimit = 32
req.predicate = NSPredicate(format: "read = NO")
let state = signposter.beginInterval("fetch")
var items = (try? context.fetch(req)) ?? []
signposter.endInterval("fetch", state)
var prioritizedItems: [Item] = []