我在这里关注Android开发人员的DAO教程:
https://developer.android.com/codelabs/android-room-with-a-view-kotlin#5
他们说:
默认情况下,所有查询都必须在单独的线程上执行
房间有Kotlin协同活动支持。这允许使用suspend修饰符对查询进行注释,然后从协程或另一个suspend函数调用查询。
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()
没有定义为挂起函数?
在协程中,流是一种可以顺序发出多个值的类型,而不是只返回单个值的挂起函数。例如,您可以使用流从数据库接收实时更新。
@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中看到源代码。