为什么 Room 中的查询函数不需要在 Kotlin 中添加 suspend 关键字?

Hel*_*oCW 11 kotlin kotlin-coroutines

我正在学习 Kotlin 的协程。

代码 A 来自北极https://github.com/googlecodelabs/android-room-with-a-view

我发现插入和删除功能添加了关键字 suspend。

为什么 Room 中的查询函数不需要getAlphabetizedWords()在 Kotlin 中添加 suspend 关键字?我认为有些查询函数需要花费很长时间来操作,因此需要在协程中运行。

代码A

@Dao
interface WordDao {

    // LiveData is a data holder class that can be observed within a given lifecycle.
    // Always holds/caches latest version of data. Notifies its active observers when the
    // data has changed. Since we are getting all the contents of the database,
    // we are notified whenever any of the database contents have changed.
    @Query("SELECT * from word_table ORDER BY word ASC")
    fun getAlphabetizedWords(): LiveData<List<Word>>

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun insert(word: Word)

    @Query("DELETE FROM word_table")
    suspend fun deleteAll()
}
Run Code Online (Sandbox Code Playgroud)

Gle*_*val 8

您不需要以异步方式进行该调用,因为它已经在幕后以这种方式工作。如果您只需要该List<Word>对象(不需要 LiveData),那么最好将该函数设置为可挂起,以便从协程或另一个挂起函数中调用它。

当数据库更新时,Room 会生成所有必要的代码来更新 LiveData 对象。生成的代码在需要时在后台线程上异步运行查询。此模式对于保持 UI 中显示的数据与数据库中存储的数据保持同步非常有用。

您可以在Android 开发文档指南的“在 Room 中使用 LiveData”部分查看此信息并了解有关 LiveData 的更多信息。