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 {}
}
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:
dispatch_async
.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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With