Android Kotlin Realm正确的方法来查询+更新异步

我最近遇到了一个问题,在内存中有一个RealResult对象列表,并在视图中显示它。 用户点击后,当前显示的项目应该被标记为已删除(property 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 。 我这样解决了,我不知道这是对的。 而不是给项目对象的更新功能,我给对象的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) } }) } } 

im不确定的问题是异步事务中查询的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.

编辑2:尝试了这一点,并显示不同的线程上的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 } }