HelloCW
HelloCW

Reputation: 2235

Why needn't the query function in Room add suspend keyword in Kotlin?

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()
}

Upvotes: 11

Views: 3185

Answers (2)

ferraro
ferraro

Reputation: 342

In a more precise way !!

Especially from version room 2.1 , queries support suspend keyword, This means, these queries marked with suspend will automatically get called in another thread by the room library itself, so these room queries are main safe.

And also additionally, if the return type is LiveData or flow, then suspend keyword is not necessary, because under the hood room will take heavy lifting and whenever data is changed it will provide the data at the observer end.

Upvotes: 0

Glenn Sandoval
Glenn Sandoval

Reputation: 3745

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.

Upvotes: 8

Related Questions