android - 房间 - return 查询的数据计数
android - room - return count of data by query
我想 return 从某个查询到我的视图的行数,我正在使用视图模型
这是我的 DAO class:
@Query("select COUNT(id) from ${db_cardsTable} where date_review>=:date and catId=:catId")
fun getNumUnread(catId: String,date:String): Int
我通过以下代码在我的 viewModel 中获取它:
class CardViewModel(private val model: CardModel) : ViewModel() {
var num = MutableLiveData<Int>()
fun haveCardForReading(catId: String,date:String): LiveData<Int> {
val dbConnection = DbConnection.getInstance(MyApp.INSTANCE)!!
val cardDao = dbConnection.CardDao()
Observable.just(DbConnection)
.subscribeOn(Schedulers.io())
.subscribe({ db ->
num.value=cardDao.getNumUnread(catId,date)
}, { error ->
Log.v("this", "ErrorNumCat ${error.localizedMessage}")
})
return num
}
这是我的 activity class 读取值:
vm.haveCardForReading(catId,LastUpdate(this).makeCurrectDate())
.observe(this, Observer {
Log.v("this","cardsToRead $it")
}
})
通过 运行 我的代码,我得到这个错误:
无法在后台线程上调用 setValue
我该如何解决这个问题?我只需要 return 查询的行数
使用 postValue()
,而不是 value=
,更新 MutableLiveData
。
或者,使用 LiveDataReactiveStreams
将您的 Observable
转换为 LiveData
,而不是手动进行。
我想 return 从某个查询到我的视图的行数,我正在使用视图模型
这是我的 DAO class:
@Query("select COUNT(id) from ${db_cardsTable} where date_review>=:date and catId=:catId")
fun getNumUnread(catId: String,date:String): Int
我通过以下代码在我的 viewModel 中获取它:
class CardViewModel(private val model: CardModel) : ViewModel() {
var num = MutableLiveData<Int>()
fun haveCardForReading(catId: String,date:String): LiveData<Int> {
val dbConnection = DbConnection.getInstance(MyApp.INSTANCE)!!
val cardDao = dbConnection.CardDao()
Observable.just(DbConnection)
.subscribeOn(Schedulers.io())
.subscribe({ db ->
num.value=cardDao.getNumUnread(catId,date)
}, { error ->
Log.v("this", "ErrorNumCat ${error.localizedMessage}")
})
return num
}
这是我的 activity class 读取值:
vm.haveCardForReading(catId,LastUpdate(this).makeCurrectDate())
.observe(this, Observer {
Log.v("this","cardsToRead $it")
}
})
通过 运行 我的代码,我得到这个错误:
无法在后台线程上调用 setValue
我该如何解决这个问题?我只需要 return 查询的行数
使用 postValue()
,而不是 value=
,更新 MutableLiveData
。
或者,使用 LiveDataReactiveStreams
将您的 Observable
转换为 LiveData
,而不是手动进行。