[英]How to get callback from Room Database android Kotlin
I want to get just row count as Int value from room database, not from initialized LiveData
such as livedata.value?.size
我只想从房间数据库中获取行数作为 Int 值,而不是从初始化的
LiveData
例如livedata.value?.size
Dao class道类
@Dao
interface MyDao {
@Query("SELECT COUNT(*) FROM User")
fun getUserCount(): Int
}
Repository class存储库类
class MyRepository(private val myDao: MyDao) {
fun getUserCount() = myDao.getUserCount()
}
ViewModel class视图模型类
class MyViewModel(application: Application) : AndroidViewModel(application) {
fun getUserCount() = myRepository.getUserCount()
}
This is what I want.这就是我要的。 But as you know we need to access room database at background thread, not at mainthread
但是你知道我们需要在后台线程访问房间数据库,而不是在主线程
so I changed the code like this所以我改变了这样的代码本
Dao class道类
@Dao
interface MyDao {
@Query("SELECT COUNT(*) FROM User")
suspend fun getUserCount(): Int
}
Repository class存储库类
class MyRepository(private val myDao: MyDao) {
suspend fun getUserCount() = myDao.getUserCount()
}
ViewModel class视图模型类
class MyViewModel(application: Application) : AndroidViewModel(application) {
fun getUserCount() = viewModelScope.launch {
myRepository.getUserCount()
}
}
if row count is 1, How can I get "1" as callback?如果行数为 1,我怎样才能得到“1”作为回调?
Use COUNT使用 COUNT
@Query("SELECT COUNT(column_name or primary key column name) from table_name ")
fun getCount(): Long
call getCount()
from repository从存储库调用
getCount()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.