After writing to a Realm in background thread, the main thread doesn't see updated data After writing to a Realm in background thread, the main thread doesn't see updated data multithreading multithreading

After writing to a Realm in background thread, the main thread doesn't see updated data


Realm instances on threads with runloops, such as the main thread, update to the latest version of the data in the Realm file as a result of a notification being posted to their thread's runloop. A time window exists between committing a write transaction on a background thread and when that notification is received by the other thread's runloop, and due to the order that CFRunLoop processes its dispatch queue relative to its notification sources, it's not uncommon for a dispatch_async to the main queue performed immediately after a write transaction is committed to be serviced before the notification can be delivered.

There are a couple of ways to address this issue:

  • Use one of Realm's notification mechanisms, such as collection notifications, to react to the changes you made on the background thread rather than explicitly using dispatch_async.
  • Explicitly call Realm.refresh() at the top of the block you dispatch to the main queue to have it bring itself to the latest version, whether or not the thread has had a chance to process the notification that triggers the automatic refresh.