Monday 26 October 2020

How can I get the query result at once when I use Room?

I hope to get the total of all records with Room database at once. But, normally Room use background thread to query record asynchronously.

If I use getTotalOfVoiceAsLiveData() in Code A, it will return LiveData<Long>, you know that LiveData variable is lazy, maybe the result is null.

If I use getTotalOfVoice() in Code A, I will get error because I can't use return in viewModelScope.launch{ }.

How can I get the total of all records at once with Room database?

Code A

class HomeViewModel(val mApplication: Application, private val mDBVoiceRepository: DBVoiceRepository) : AndroidViewModel(mApplication) {

    fun getTotalOfVoice():Long {
        viewModelScope.launch {
            return mDBVoiceRepository.getTotalOfVoice()   //It will cause error
        }
    }

    fun getTotalOfVoiceAsLiveData(): LiveData<Long>{
        return mDBVoiceRepository.getTotalOfVoiceAsLiveData() //It's lazy, maybe the result is null.
    }

}


class DBVoiceRepository private constructor(private val mDBVoiceDao: DBVoiceDao){
    suspend  fun getTotalOfVoice() = mDBVoiceDao.getTotalOfVoice()

    fun getTotalOfVoiceAsLiveData() = mDBVoiceDao.getTotalOfVoiceAsLiveData()
}



@Dao
interface DBVoiceDao{
   @Query("SELECT count(id) FROM voice_table")
   suspend fun getTotalOfVoice(): Long

   //When Room queries return LiveData, the queries are automatically run asynchronously on a background thread.
   @Query("SELECT count(id) FROM voice_table")
   fun getTotalOfVoiceAsLiveData(): LiveData<Long>
}


from How can I get the query result at once when I use Room?

No comments:

Post a Comment