Fix race condition on loading notifications

This commit is contained in:
Shadowfacts 2020-05-06 19:32:32 -04:00
parent aa625a41f5
commit ebbfc7a132
Signed by: shadowfacts
GPG Key ID: 94A5AB95422746E5
2 changed files with 38 additions and 26 deletions

View File

@ -119,4 +119,19 @@ class MastodonCachePersistentStore: NSPersistentContainer {
}
}
func addAll(notifications: [Pachyderm.Notification], completion: (() -> Void)? = nil) {
backgroundContext.perform {
let statuses = notifications.compactMap { $0.status }
let accounts = notifications.map { $0.account }
statuses.forEach { self.upsert(status: $0, incrementReferenceCount: true) }
accounts.forEach { self.upsert(account: $0) }
if self.backgroundContext.hasChanges {
try! self.backgroundContext.save()
}
completion?()
statuses.forEach { self.statusSubject.send($0.id) }
accounts.forEach { self.accountSubject.send($0.id) }
}
}
}

View File

@ -63,17 +63,16 @@ class NotificationsTableViewController: EnhancedTableViewController {
self.groups.append(contentsOf: groups)
self.mastodonController.persistentContainer.addAll(statuses: notifications.compactMap { $0.status })
self.mastodonController.persistentContainer.addAll(accounts: notifications.map { $0.account })
self.newer = pagination?.newer
self.older = pagination?.older
self.mastodonController.persistentContainer.addAll(notifications: notifications) {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
// MARK: - Table view data source
@ -142,11 +141,9 @@ class NotificationsTableViewController: EnhancedTableViewController {
}
self.groups.append(contentsOf: groups)
self.mastodonController.persistentContainer.addAll(statuses: newNotifications.compactMap { $0.status })
self.mastodonController.persistentContainer.addAll(accounts: newNotifications.map { $0.account })
self.older = pagination?.older
self.mastodonController.persistentContainer.addAll(notifications: newNotifications) {
DispatchQueue.main.async {
UIView.performWithoutAnimation {
self.tableView.insertRows(at: newIndexPaths, with: .automatic)
@ -155,6 +152,7 @@ class NotificationsTableViewController: EnhancedTableViewController {
}
}
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
@ -219,13 +217,11 @@ class NotificationsTableViewController: EnhancedTableViewController {
self.groups.insert(contentsOf: groups, at: 0)
self.mastodonController.persistentContainer.addAll(statuses: newNotifications.compactMap { $0.status })
self.mastodonController.persistentContainer.addAll(accounts: newNotifications.map { $0.account })
if let newer = pagination?.newer {
self.newer = newer
}
self.mastodonController.persistentContainer.addAll(notifications: newNotifications) {
DispatchQueue.main.async {
let newIndexPaths = (0..<groups.count).map {
IndexPath(row: $0, section: 0)
@ -241,6 +237,7 @@ class NotificationsTableViewController: EnhancedTableViewController {
}
}
}
}
}