gpt4 book ai didi

kotlin - 为什么在Kotlin中不需要在Room中的查询功能添加suspended关键字?

转载 作者:行者123 更新时间:2023-12-02 12:51:34 28 4
gpt4 key购买 nike

我正在学习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()
}

最佳答案

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

Room generates all the necessary code to update the LiveData object when a database is updated. The generated code runs the query asynchronously on a background thread when needed. This pattern is useful for keeping the data displayed in a UI in sync with the data stored in a database.



您可以查看此信息并在androidt开发文档指南中的 “将LiveData与房间一起使用”的部分 here下了解更多信息。

关于kotlin - 为什么在Kotlin中不需要在Room中的查询功能添加suspended关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60922788/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com