0
votes

Good day, I'm working through the coroutines with room codelab and I have some doubt as to when it's okay to simply call a databaseDao from a ViewModel and when you need to put it inside a suspend fun and launch it from a Coroutine with Dispatchers(IO).

In particular, in the code, which can be found here, inside SleepTrackerViewModel on line 37 they declare a val directly in the class like this:

private val nights = database.getAllNights()

Where the database is the dao and getAllNights is a query and it's called without any Coroutine or suspend fun. Shouldn't this be done from a coroutineScope within a suspend fun?

Thanks in advance!

1

1 Answers

0
votes

As seen in the SleepDatabaseDao, getAllNights() is defined as:

fun getAllNights(): LiveData<List<SleepNight>>

Getting a LiveData does not need to be called on a background thread or from within a coroutine scope.