Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

ios - Realm: How to receive change notifications from a different thread?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...