'Why Query with LiveData doesn't needs to be added to BG Thread
I am trying understand room db with LiveData. I was following one of Googles videos on Room. In the project they have specified:
In Dao:
@Query("SELECT * FROM daily_sleep_quality_table ORDER BY nightId DESC")
fun getAllNights(): LiveData<List<SleepNight>>
In ViewModel:
private val nights = database.getAllNights()
In the viewModel, they are directly calling getAllNights(). And for other Dao methods which doesn't have LiveData they are calling from a suspend function. How does this work?
Solution 1:[1]
liveData is a good structure that when its values changed, all of its callbacks in other places reflect the changes so you can use this in place of suspend func in coroutines but it is not recommended i suggest you always use coroutines suspend function in Dao class as you there is alo f benefit in coroutine for long runtime functions such as reading from database.
Solution 2:[2]
Use LiveData with Room
The Room persistence library supports observable queries, which return LiveData objects. Observable queries are written as part of a Database Access Object (DAO).
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 read more about Room and DAOs in the Room persistent library guide.
For more details read: https://developer.android.com/topic/libraries/architecture/livedata#use_livedata_with_room
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | soheil ghanbari |
| Solution 2 | pepperlove |
