我正在Kotlin开发一个应用程序,该应用程序使用房间数据库,基于众所周知的示例"带视图的房间数据库">
相关代码片段:
主要活动:
siniestroViewModel.insert(taller)
视图模型:
fun nuevo(siniestro: Siniestro) = viewModelScope.launch(Dispatchers.IO) {
repository.nuevo(siniestro)
}
存储库:
suspend fun nuevo(siniestro: Siniestro){
siniestroDao.nuevo(siniestro)
}
刀:
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun nuevo(siniestro: Siniestro)
此代码可防止插入重复的记录,并且可以按预期工作。问题是我如何检测插入失败,以显示Toast的警告消息。
我在调试应用程序时遇到了类似的问题。经过一点搜索,我找到了一种方法来检测和处理插入操作的结果,这对我帮助很大。它也可能帮助其他人。基于上面提供的代码:
刀:
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun nuevo(siniestro: Siniestro): Long
@Transaction
suspend fun nuevoWithToast(siniestro: Siniestro) {
val result = nuevo(siniestro)
if (result == -1L) {
//Use a Toast or Log to show failed operation
//An update method can also be called depending on the strategy
}
}
这里的关键是:带有@Insert
注释的方法可以返回Long
值。最后调用nuevoWithToast
而不是nuevo
存储库:
suspend fun nuevo(siniestro: Siniestro){
siniestroDao.nuevoWithToast(siniestro)
}