After writing to Realm in the background stream, the main stream does not see the updated data

  • Clear the database.
  • Create an API call to retrieve new data.
  • Write the data received from the API to the database in the background thread.
  • Reading data from a database in the main stream and displaying the user interface.

In step 4, the data should contain the most recent data, but we do not see 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 {} } 
+5
source share
1 answer

Real instances on streams with runloops, such as the main stream, are updated to the latest version of the data in the Realm file as a result of a notification sent to their runloop stream. There is a time window between the execution of a write transaction in the background thread and upon receipt of this notification by another runloop thread and because of the order that CFRunLoop processes the send queue regarding notification sources, it is not uncommon for dispatch_async to go to the main queue executed immediately after the transaction Records completed to be serviced before the notification is delivered.

There are several ways to solve this problem:

  • Use one of the Realm notification mechanisms, such as crash notification, to respond to changes you make to the background thread, rather than explicitly using dispatch_async .
  • I will explicitly call Realm.refresh() at the top of the block that you send to the main queue so that it brings itself to the latest version, does the thread have the ability to process a notification that triggers automatic updating.
+2
source

Source: https://habr.com/ru/post/1271088/


All Articles