Search code examples
androidsqlmultithreadingkotlinandroid-room

How to query room database using kotlin coroutines?


I have the following data table

@Entity(tableName = "day_table")
data class DayData(
    @PrimaryKey(autoGenerate = true)
    var dayID: Long =0L,
    @ColumnInfo(name = "step_date")
    var stepDate : String = "" ,
    @ColumnInfo(name = "step_count")
    var stepCount : Int = 0,
    @ColumnInfo(name = "step_goal")
    var stepGoal : Int = 0
)

In my dao I have

    @Insert
    fun insert(day: DayData)

    @Update
    fun update(day: DayData)

    @Query("SELECT EXISTS(SELECT * FROM day_table WHERE step_date = :queryDate)")
    suspend fun doesDayExist(queryDate:String) : Boolean

In the viewModel class I have:

 private fun initDay(){
        //check if this day is in the db

        var exist :Boolean = false
        viewModelScope.launch {
            exist = doesDayExist()
        }

        //if day doesnt exist in db, create it
        if (!exist)
        {
            onNewDay()
        }

    }

    //function to check if given date is in db
    private suspend fun doesDayExist(): Boolean{
        return dayDatabaseDao.doesDayExist(dts.toSimpleString(currDate.time))
    }

My insert and update work perfectly fine, I have checked that the data is in the database as expected. The value of exist does not change even though I am calling the query, when I set it to true it stays true, when set to false initially it stays false. What am I missing?


Solution

  • You are setting exist in Coroutine Function. You have to carry code to coroutinescope.

        viewModelScope.launch{
            exist = doesDayExist()
            if (!exist)
              {
                onNewDay()
              }
        }