我在這里關注有關 Android 開發人員的 DAO 教程:
https://developer.android.com/codelabs/android-room-with-a-view-kotlin#5
他們說:
默認情況下,所有查詢都必須在單獨的執行緒上執行。
Room 支持 Kotlin 協程。這允許您的查詢使用掛起修飾符進行注釋,然后從協程或另一個掛起函式中呼叫。
道界面如下:
@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()不定義為掛起函式?
uj5u.com熱心網友回復:
在協程中,流是一種可以順序發出多個值的型別,而不是只回傳單個值的掛起函式。例如,您可以使用流從資料庫接收實時更新。
@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中查看源代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/418641.html
標籤:
下一篇:此回圈的功能等效項
