Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  1. Clear the database.
  2. Make an API call to get the new data.
  3. Write the data retrieved from the API into the database in a background thread.
  4. Read data from the database on the main thread and render UI.

In step 4 the data should be the latest data, but we're not seeing any data.

// remark: all main thread shared a realm object
DBManager.deleteAll()
// call api success, get newdata
DispatchQueue.global(qos: .background).async { 
    DBManager.initDBData(<newdata>)
    DispatchQueue.main.async {
        print("has data?????", DBManager.getBrands().count)
     }
 }

// when write
func write() {
    let realmBackgroud = try! Realm()
    try! realmBackgroud.write {}
 }
like image 670
苏文梁 Avatar asked Aug 22 '17 05:08

苏文梁


1 Answers

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.
like image 181
bdash Avatar answered Nov 16 '22 16:11

bdash