简体   繁体   English

如何使用kotlin协程查询房间数据库?

[英]How to query room database using kotlin coroutines?

I have the following data.table我有以下 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:在 viewModel class 我有:

 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.即使我正在调用查询, exist的值也不会改变,当我将它设置为 true 时它保持为 true,当最初设置为 false 时它保持为 false。 What am I missing?我错过了什么?

You are setting exist in Coroutine Function. You have to carry code to coroutinescope.您正在设置 exist in Coroutine Function。您必须将代码携带到 coroutinescope。

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

Launching a coroutine queues it up, but the current function continues while that coroutine starts in the background.启动协程会将其排入队列,但当前的 function 会在该协程在后台启动时继续运行。 Your function returns before the coroutine has finished its work.您的 function 在协程完成工作之前返回。 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.协程中的代码是同步的,但启动协程是异步的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM