All the queries to the database are written in CouroutineScope. But this line of code in just inside of ViewModel class. And it's not blocking the UI thread. I don't understand how is it executing
private val nights = database.getAllNights()
You can see the whole repo in this link
The Dao function getAllNights()
is returning a LiveData:
fun getAllNights(): LiveData<List<SleepNight>>
This return is done immediately upon calling that function, without waiting for the results to load from the database. The LiveData can then be observed to be notified when the data is loaded (on a background thread, asynchronously). It will also notify observers if the result of the query changes later on.
In contrast, if you take one of the calls where it's wrapped inside a launch
and a switch to the IO
dispatcher, such as getTonight()
:
fun getTonight(): SleepNight?
A Dao function like this will block the thread until it gets the result of the query, which is why it's important that you take care of going to a background thread before calling it.