Search code examples
android-roomlazycolumn

How to update lazyColumn's item using the Flow list from room?


As below code showed, I got the list(type: Flow<List<T>>),

how can I use it to update lazyColumn's item, so when the room data changed, lazyColumn updates items accordingly?

Many thanks.

@Composable
fun SomeContent(context: Context) {
    // get the view model ref
    val viewModel: SomeViewModel =
        viewModel(factory = SomeViewModelFactory(Db.getInstance(context)))

    // get the list from room, it is a Flow list
    val list = viewModel.sumDao.getAllRows()

    LazyColumn(
    ) {
        // I need to use the list in below, but got errors, how to do?
        items(list.size) {
        SomeListItem(list[it])
        }
    }
}

Solution

  • You must collect your FlowList as follows

    val list = viewModel.sumDao.getAllRows().collectAsState(initial = emptyList())
    

    Instead of items, use itemsIndexed

    itemsIndexed(list.value) {idx, row -> SomeListItem(row)}
    

    Let me know if the above works.