Android DAO何时使用挂起函数

yra*_*as8 7 android kotlin kotlin-coroutines

我正在关注有关 Android 开发人员的 DAO 教程:

https://developer.android.com/codelabs/android-room-with-a-view-kotlin#5

他们说:
默认情况下,所有查询都必须在单独的线程上执行。
Room 有 Kotlin 协程支持。这允许您的查询使用挂起修饰符进行注释,然后从协程或另一个挂起函数调用。

Dao接口如下:

@Dao
interface WordDao {

    @Query("SELECT * FROM word_table ORDER BY word ASC")
    fun getAlphabetizedWords(): 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)

为什么getAlphabetizedWords()不定义为挂起函数?

小智 7

在协程中,流是一种可以按顺序发出多个值的类型,而不是仅返回单个值的挂起函数。例如,您可以使用流从数据库接收实时更新。

@Dao
interface WordDao {

    // The flow always holds/caches latest version of data. Notifies its observers when the
    // data has changed.
    @Query("SELECT * FROM word_table ORDER BY word ASC")
    fun getAlphabetizedWords(): Flow<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)

你可以在 Github 中查看源代码