Search code examples
androidkotlinandroid-room

Why is information not being retrieved from the Room Database when returned as a Flow?


Everything was working fine initially, but later I added a table to the database. I have wiped all data and started fresh, so I don't think its a migration issue.

The initial tables are working fine as expected. For the new table when I run the query through app inspector then it works fine within the app inspector. However when the query (specified in the dao) is called through the ViewModel, it returns an empty list.

within the DAO:

@Query("SELECT * FROM PropTable")
fun readPropReport(): Flow<List<PropReport>>

within the viewModel:

val _propReportsU = dao.readPropReport().stateIn(viewModelScope, SharingStarted.WhileSubscribed(500),
emptyList())
Log.i("Prop Function", "Prop Reports 'U': ${_propReportsU.value}")

The Log shows that the returned result is an empty list, but as I said the table is not empty when running the query through the app inspector it is not empty.

When the query is run I expected to see the values in the table, however it results in an empty set. Running the query through the app inspector returns the expected values from the table.

Room tutorial I followed: https://www.youtube.com/watch?v=bOd3wO0uFr8&ab_channel=PhilippLackner


Solution

  • readPropReport returns a Flow that you convert to a StateFlow by calling stateIn.

    A StateFlow is an asynchronous datatype that represents a value that can change over time. It is initialized with an emptyList() until the database returns the result from the query.

    You log its value directly after it was created, before the database had enough time to execute the query, so you get an empty list (the initial value). If you would log the value again after some time, it would contain the expected results.

    But Flows are usually meant to be collected like this:

    _propReportsU.collect {
        Log.i("Prop Function", "Prop Reports 'U': $it")
    }
    

    Now, everytime the value of _propReportsU changes, a log message is printed. Should be twice for you: First an empty list, then the results from your query. Note that collect is a suspend function, so it must be called from a coroutine or another suspend function.


    The common pattern for flows in the view model is different from what you do, though. Usually you want to expose the flow as a property for the UI can collect:

    class MyViewModel(
        dao: MyDao,
    ) : ViewModel() {
        val propReportsU = dao.readPropReport()
            .stateIn(
                scope = viewModelScope,
                started = SharingStarted.WhileSubscribed(5_000),
                initialValue = emptyList(),
            )
    }
    

    When you use Compose for your UI, the collection of the flow would look like this:

    @Composable
    fun MyComposable(myViewModel: MyViewModel = viewModel()) {
        val propReports: List<PropReport> by myViewModel.propReportsU.collectAsStateWithLifecycle()
    }
    

    propReports will now always contain the most current state of the list: Empty at first, then, after the query finished, the query's result.