房间数据库仅在App重新启动后才返回更新的值
我正在使用以下视图模型类的方法在房间数据库中插入和删除一行
fun insert(rules: TableRules) = viewModelScope.launch {
repository.insert(rules)
}
fun delete(id: Int) = viewModelScope.launch {
repository.delete(id)
}
,并使用此方法的DAO类方法检索数据
@Query("SELECT * FROM rules_table")
fun getAlphabetizedRules(): List<TableRules>
,但我没有获得更新数据。 即,当我添加一行然后重试时,我不会再添加了行。 我关闭了我的应用程序,从最近的应用列表中删除,重新启动应用程序然后重新检测,然后我将获得该行。
同样的事情也发生在删除时。
我缺少我上面的东西。
i am inserting and deleting a row in room database using following methods of ViewModel class
fun insert(rules: TableRules) = viewModelScope.launch {
repository.insert(rules)
}
fun delete(id: Int) = viewModelScope.launch {
repository.delete(id)
}
and retriving the data using this this method of DAO class
@Query("SELECT * FROM rules_table")
fun getAlphabetizedRules(): List<TableRules>
but i am not getting update data.
i.e when i add one row and then retrive, i will not get newly added row.
i close my app, remove from recent app list, start app again then retrive, then i will get that row.
same thing happens in case of delete also.
what i am missing i above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
推出将来将完成的Coroutine队列工作。如果您启动Coroutine,然后立即检查桌子状态,而无需等待Coroutine完成,则您会有比赛状态,并且很可能会恢复较早的状态。
您需要调用
getAlphabetizedRules()
从启动的同一coroutine内部进行调用insert()
或 delete()数据库更改。或者,您可以创建一个新的Coroutine或暂停功能,该功能
join
s从您现有insert()
and delete() function中返回的作业。例如:顺便说一句,在您的dao中,
getAlphabetizedRules()
应标记为suppend
功能,以使其更易于正确使用(不必使用使用context(dispatchers.io){}
每次调用时。Launching a coroutine queues up work that will complete in the future. If you launch a coroutine and then immediately check the state of the table without waiting for the coroutine to finish, you have a race condition and will likely get the earlier state returned.
You need to call
getAlphabetizedRules()
from inside the same coroutine that you launch to callinsert()
ordelete()
so it is happening after the database change.Or alternatively, you can create a new coroutine or suspend function that
join
s the returned Job from your existinginsert()
anddelete()
functions. For example:By the way, in your DAO,
getAlphabetizedRules()
should be marked as asuspend
function to make it easier to use properly (not having to usewithContext(Dispatchers.IO) { }
every time you call it.用@rawquery注释而不是普通@Query标记DAO方法。
Mark the DAO method with @RawQuery annotation instead of normal @Query.