title: How to: Using Combine to react to CoreData changes in the background
body: <p>I want to achieve the following: Whenever someone triggers a CoreData save (ie. <code>NSManagedObjectContextDidSave</code> notification gets sent), I'd like to perform some <strong>background</strong> calculation based the changed NSManagedObject. Concrete example: Assume in a notes app, I want to asynchronously calculate the total number of words in all notes.</p>
  <p>The problem currently lies with the fact that NSManagedObject context is explicitly bound to thread and you are discouraged from using <code>NSManagedObject</code>s outside this thread.</p>
  <p>I have setup two <code>NSManagedObjectContext</code>s in my <code>SceneDelegate</code>:</p>
  <pre class="lang-swift prettyprint-override"><code>let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
  let backgroundContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.newBackgroundContext()
  </code></pre>
  <p>I also have subscribed to the notification via <code>NotificationCenter.default.publisher(for: .NSManagedObjectContextDidSave)</code> and am receiving a save notification <em>twice</em> after I trigger only <em>one</em> <code>managedObjectContext.save()</code>. However, both notifications are sent from the same thread (which is the UIThread) and all <code>NSManagedObjects</code> in the user dictionary have a <code>.managedObjectContext</code> which is the <code>viewContext</code> and not the <code>backgroundContext</code>.</p>
  <p>My idea was to filter the notifications based on whether or not the associated <code>NSManagedObjectContext</code> was the background one as I assumed that the notification is also sent on the (private) DispatchQueue but it seems all notifications are sent on the UIThread and the background context is never used.</p>
  <p>Any idea on how to solve this? Is this a bug? How can I retrieve notifications based on the <code>backgroundContext</code> with downstream tasks being run on the associated DispatchQueue?</p>