Observing merges into an NSManagedObjectContext

Hi,

I have a fetch request that computes the sum of an entity's property in Core Data, more precisely the sum of unread messages in multiple chats:


let unreadCountFetchRequest = NSFetchRequest(entityName: String(describing: Chat.self))
unreadCountFetchRequest.resultType = .dictionaryResultType
let exp = NSExpressionDescription()
exp.name = "unreadCount"
exp.expression = NSExpression(forKeyPath: "@sum.unreadCount")
exp.expressionResultType = .integer64AttributeType
unreadCountFetchRequest.propertiesToFetch = [exp]
let result = try context.fetch(unreadCountFetchRequest)


To keep the value up-to-date, I need to re-execute that fetch request whenever the data has changed. I'm not sure how to do that. If I was working with only one NSManagedObjectContext for saving and reading, I would observe NSManagedObjectContextDidSave on that context, and re-do the fetch on each save.


However, I'm performing the fetch request on the viewContext, while the data comes in on a (hidden) background context. The viewContext's automaticallyMergesChangesFromParent is set to true, so that it gets updated. How do I know if new data has been merged into my context, so that I can perform a new fetch?


At the moment, I'm observing NSManagedObjectContextDidSave on all contexts (by passing nil to the observer function), but this seems wrong, doesn't it?


unreadCountObserver = NotificationCenter.default.addObserver(descriptor: NotificationCenter.managedObjectContextDidSave, object: nil) { [unowned self] payload in
    let objects = payload.updatedObjects.union(payload.jects).union(payload.insertedObjects)
    if objects.contains(where: { type(of: $0) == ChannelReadInfo.self }) {
        self.context.perform {
            // Perform fetch
        }
    }
}

Thanks!