I am new to Realm and I am trying to take advantage of the collection notifications. I have a list of movies and want to be notified whenever a movie is added or removed. I started like this:
let realm = try! Realm()
moviesDB = realm.objects(MovieDB.self).filter("isFavorite == true")
notificationToken = moviesDB!.observe() { [weak self] (changes) in
print("smth changed!")
}
This works, however I don't want to to the reading in the UI thread, but I want to receive the change notifications in the UI thread. So, I changed it to this:
notificationToken = moviesDB?.observe() { [weak self] (changes) in
print("smth changed!")
}
DispatchQueue(label: "background").async {
autoreleasepool {
let realm = try! Realm()
self.moviesDB = realm.objects(MovieDB.self).filter("isFavorite == true")
.....
}
}
It crashes with 'Realm accessed from incorrect thread.' because I created the collection in a background thread but observe it in the UI thread. So, I changed the code again to use a ThreadSafeReference:
if let threadSafeMoviesDB = self.threadSafeMoviesDB, let movies = self.uiRealm.resolve(threadSafeMoviesDB) {
notificationToken = movies.observe() { [weak self] (changes) in
print("smth changed!")
}
}
DispatchQueue(label: "background").async {
autoreleasepool {
let realm = try! Realm()
self.moviesDB = realm.objects(MovieDB.self).filter("isFavorite == true")
self.threadSafeMoviesDB = ThreadSafeReference(to: self.moviesDB!)
....
}
}
This works, but it looks like a workaround and I don't think it's the proper way to do it. Can anyone point me in the right direction?
question from:
https://stackoverflow.com/questions/66061586/realm-how-to-receive-change-notifications-from-a-different-thread 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…