Home > database >  How to query room database using kotlin coroutines?
How to query room database using kotlin coroutines?

Time:02-17

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?

CodePudding user response:

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

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

CodePudding user response:

Launching a coroutine queues it up, but the current function continues while that coroutine starts in the background. Your function returns before the coroutine has finished its work. You need to put code that you want to run after you get the result inside the coroutine.

See here for more information about asynchronous work. The code inside a coroutine is synchronous, but launching a coroutine is asynchronous.

  • Related