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

Viewed 326

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])
        }
    }
}
2 Answers

You must collect your FlowList as follows

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

Instead of items, use itemsIndexed

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

Let me know if the above works.

if using vn1gam's solution, might need to do

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