Search code examples
androidandroid-sqliteandroid-roomandroid-livedataandroid-viewmodel

android - room - return count of data by query


I want to return count of rows from a certain query to my view ,I'm using view model

this is my DAO class:

 @Query("select COUNT(id) from ${db_cardsTable} where date_review>=:date and catId=:catId")
fun getNumUnread(catId: String,date:String): Int

I get it in my viewModel by this code :

 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
    }

and this is my activity class to read the value :

vm.haveCardForReading(catId,LastUpdate(this).makeCurrectDate())
            .observe(this, Observer {
                Log.v("this","cardsToRead $it")

            }
        })

by running my code ,I get this error :

Cannot invoke setValue on a background thread

How can I fix this ? I just need to return the number of rows by query


Solution

  • Use postValue(), not value=, to update the MutableLiveData.

    Or, use LiveDataReactiveStreams to convert your Observable into a LiveData, instead of doing it manually.