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 } }
- 运行kotlin realm demo canon
- 使用@PrimaryKey初始化Realm对象0(零)在第二个对象上失败
- Realm&Kotlin:DefaultRealmModuleMediator.java – > error:unreachable statement
- 无法在RealmObject子类中创建ArrayList
- Kotlin – 如何使外部类只读字段
- 用关闭的交易来写Realm Daos
- 如何在我的Realm迁移代码中指定一个盒装字段可以为空?
- TransformException:java.util.zip.ZipException:重复条目:io / realm / annotations / Ignore.class
- Android,领域,Gradle:错误:注释处理器:找不到RealmProcessor