[英]Android Kotlin Realm Proper Way to Query+Update Async
我最近遇到了一个问题,其中我在内存中存储了对象的RealResult列表,并在视图中显示了该列表。 用户单击后,当前显示项目应标记为已删除(领域isDeleted
)
所以我只是从懒惰的RealmResults
列表中获取该对象,打开一个事务并将其标记为已删除。 由于RealmResults是自动更新的,因此我有一个绑定到notifityDataSetChanged
的更改侦听notifityDataSetChanged
。 除了以下警告,一切正常:
Mixing asynchronous queries with local writes should be avoided. Realm will convert any async queries to synchronous in order to remain consistent. Use asynchronous writes instead
这是有问题的,因为我的列表很大,而且我不希望查询变得sync
。 我是用这种方式解决的,我不知道这是对的。 我没有将item对象提供给update函数,而是给出了对象的id,然后执行以下操作:
Realm.getDefaultInstance().use { realm ->
realm.executeTransactionAsync {
// find the item
realm.where(ItemRealm::class.java)
.equalTo(ItemRealm.ID, itemId).findFirstAsync()
.addChangeListener(object : RealmChangeListener<ItemRealm> {
override fun onChange(element: ItemRealm) {
element.deleted = true
element.removeChangeListener(this)
}
})
}
}
不确定的问题是异步事务中查询的async
部分。
编辑。 实际上,它会引发java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
Edit2:尝试过此操作并在不同线程上显示Realm访问权限:
fun setItemDeleted(itemId: Long) {
// write so new realm instance
Realm.getDefaultInstance().use { realm ->
realm.executeTransactionAsync {
// find the item
val item = realm.where(ItemRealm::class.java)
.equalTo(ItemRealm.TIMESTAMP, itemId).findFirst()
item?.userDeleted = true
}
}
}
executeTransactionAsync()
所有内容都在后台线程上运行,因此您应该使用同步方法在其中获取对象。
Realm.getDefaultInstance().use { realm ->
realm.executeTransactionAsync { bgRealm ->
// find the item
val item = bgRealm.where(ItemRealm::class.java)
.equalTo(ItemRealm.ID, itemId).findFirst()
item?.deleted = true
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.