3
votes

I'm learning Coroutines of Kotlin.

The Code A is from the arctical https://github.com/googlecodelabs/android-room-with-a-view

I find that the keyword suspend are added for the Insert and Delete function.

Why needn't the query function getAlphabetizedWords() in Room add suspend keyword in Kotlin? I think that some query function need to spend long time to operate, so it need to run in Coroutines.

Code 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()
}
1
Actually the read query function should add suspend . See suspend fun getUsers(): List<User> medium.com/androiddevelopers/room-coroutines-422b786dc4c5 . Same author. - Raymond Chenon

1 Answers

3
votes

You don't need to make that call in an asynchronous manner since it works that way already under the hood. If you needed only the List<Word> object (no LiveData) then it would be better if you make that function suspendable to call it from a coroutine or another suspend function.

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.

You can check this information and learn more about LiveData on the Android Development Documentation Guides under the "Use LiveData with Room" section here.