DAO 何时使用挂起函数 android
DAO when to use suspend function android
我正在关注 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()
}
为什么getAlphabetizedWords()
没有定义为挂起函数?
在协程中,流是一种可以按顺序发出多个值的类型,这与 return 仅发出一个值的挂起函数相反。例如,您可以使用流从数据库接收实时更新。
@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()
}
您可以在 Github 中看到 source code。
我正在关注 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()
}
为什么getAlphabetizedWords()
没有定义为挂起函数?
在协程中,流是一种可以按顺序发出多个值的类型,这与 return 仅发出一个值的挂起函数相反。例如,您可以使用流从数据库接收实时更新。
@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()
}
您可以在 Github 中看到 source code。