如何在不同线程中克隆RealmQuery?
问题:
- 在 X 线程中创建 RealmQuery。
- 查询 RealmResults 是同一个线程。
- 如果结果为空,则在 Y 线程中从服务器获取数据。
- 在后台线程中将数据插入 Realm (Y)。 <-- Realm 的新实例
- 使用与
1
中相同的过滤器重新查询在 Z 线程中。 - 在主线程中返回结果。
截至目前,我得到 java.lang.IllegalStateException: Realm accessed from incorrect thread.
尝试克隆使用,RealmQuery.createQueryFromResult(RealmResults<E> queryResults)
.在内部克隆使用结果的相同 Realm 实例。
如果 queryResults
克隆将如何表现?是空的?
如果能在RxJava2中克隆就更好了。
最佳答案
Re-query with same filters as in 1 in Z Thread.
Return results in Main Thread.
好的,这是完全没有必要的,因为您可以创建一个 RealmQuery 并存储对 RealmResults 的字段引用,向其添加一个 RealmChangeListener,当您在后台线程上插入 Realm 时,它会自动更新 RealmResults 并调用RealmChangeListener。
所以你不需要“在 Z 线程中使用相同的过滤器重新查询”(因为 Realm 的 findAllSortedAsync()
已经在后台线程上查询),你不需要手动在主线程中返回结果,因为 findAllSortedAsync()
已经这样做了。
解决方案:使用 Realm 的通知系统(和异步查询 API)。阅读文档:https://realm.io/docs/java/latest/#notifications
关于android - 不同线程中的 Realm Clone RealmQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44035272/