Fix potential race between adding notification to NSManagedObjectContext and displaying VC

This commit is contained in:
Shadowfacts 2024-11-26 23:26:35 -05:00
parent e8a492ef7d
commit 670047af6f
2 changed files with 9 additions and 6 deletions

View File

@ -375,13 +375,14 @@ class MastodonCachePersistentStore: NSPersistentCloudKitContainer, @unchecked Se
} }
} }
func addAll(notifications: [Pachyderm.Notification], completion: (() -> Void)? = nil) { func addAll(notifications: [Pachyderm.Notification], in context: NSManagedObjectContext? = nil, completion: (() -> Void)? = nil) {
backgroundContext.perform { let context = context ?? backgroundContext
context.perform {
let statuses = notifications.compactMap { $0.status } let statuses = notifications.compactMap { $0.status }
let accounts = notifications.map { $0.account } let accounts = notifications.map { $0.account }
statuses.forEach { self.upsert(status: $0, context: self.backgroundContext) } statuses.forEach { self.upsert(status: $0, context: context) }
accounts.forEach { self.upsert(account: $0, in: self.backgroundContext) } accounts.forEach { self.upsert(account: $0, in: context) }
self.save(context: self.backgroundContext) self.save(context: context)
completion?() completion?()
statuses.forEach { self.statusSubject.send($0.id) } statuses.forEach { self.statusSubject.send($0.id) }
accounts.forEach { self.accountSubject.send($0.id) } accounts.forEach { self.accountSubject.send($0.id) }

View File

@ -48,7 +48,9 @@ class NotificationLoadingViewController: UIViewController {
do { do {
let (notification, _) = try await mastodonController.run(request) let (notification, _) = try await mastodonController.run(request)
await withCheckedContinuation { continuation in await withCheckedContinuation { continuation in
mastodonController.persistentContainer.addAll(notifications: [notification]) { let container = mastodonController.persistentContainer
let context = container.viewContext
container.addAll(notifications: [notification], in: context) {
continuation.resume() continuation.resume()
} }
} }