SubscriptionsObservable.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import CoreData
  2. import SwiftUI
  3. class SubscriptionsObservable: NSObject, ObservableObject {
  4. private let tag = "SubscriptionsObservable"
  5. override init() {
  6. super.init()
  7. // This will force the initialization of notificationsFetchedResultsController
  8. _ = self.notificationsFetchedResultsController
  9. }
  10. private lazy var fetchedResultsController: NSFetchedResultsController<Subscription> = {
  11. let fetchRequest: NSFetchRequest<Subscription> = Subscription.fetchRequest()
  12. fetchRequest.sortDescriptors = [NSSortDescriptor(key: "topic", ascending: true)]
  13. let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: Store.shared.context, sectionNameKeyPath: nil, cacheName: nil)
  14. controller.delegate = self
  15. do {
  16. Log.d(tag, "Fetching subscriptions")
  17. try controller.performFetch()
  18. } catch {
  19. Log.w(tag, "Failed to fetch subscriptions: \(error)", error)
  20. }
  21. return controller
  22. }()
  23. private lazy var notificationsFetchedResultsController: NSFetchedResultsController<Notification> = {
  24. let fetchRequest: NSFetchRequest<Notification> = Notification.fetchRequest()
  25. fetchRequest.sortDescriptors = [NSSortDescriptor(key: "time", ascending: true)]
  26. let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: Store.shared.context, sectionNameKeyPath: nil, cacheName: nil)
  27. controller.delegate = self
  28. do {
  29. Log.d(tag, "Fetching notifications")
  30. try controller.performFetch()
  31. } catch {
  32. Log.w(tag, "Failed to fetch notifications: \(error)", error)
  33. }
  34. return controller
  35. }()
  36. var subscriptions: [Subscription] {
  37. fetchedResultsController.fetchedObjects ?? []
  38. }
  39. }
  40. extension SubscriptionsObservable: NSFetchedResultsControllerDelegate {
  41. func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
  42. Log.d(tag, "Fetching notifications")
  43. DispatchQueue.main.async {
  44. self.objectWillChange.send()
  45. }
  46. }
  47. }