Search code examples
androidandroid-jetpack-composeandroid-viewmodelandroid-jetpack-compose-lazy-column

How to get LazyRow's visible items in viewmodel


I have created a LazyRow in jetpack compose. At a certain point in the viewmodel, I want to get the list of currently visible items from that LazyRow. I know that I can get the list of visible items in the Composable function using the following code:

val listState = rememberLazyListState()
val visibleItemIds = remember {
    derivedStateOf { listState.layoutInfo.visibleItemsInfo.map { it.key.toString() } }
}

The problem is how can I pass this data to the viewmodel during a viewmodel event (not a button click etc)


Solution

  • You can add a side effect to know what are the visible items in any time.

    LaunchedEffect(visibleItemIds){
       //update your viewModel
    }
    

    You can also have a List<T> instead of State<List<String>> as in your code with:

    val state = rememberLazyListState()
    val visibleItemIds: List<Int> by remember {
        derivedStateOf {
            val layoutInfo = state.layoutInfo
            val visibleItemsInfo = layoutInfo.visibleItemsInfo
            if (visibleItemsInfo.isEmpty()) {
                emptyList()
            } else {
                visibleItemsInfo.map { it.index }
            }
        }
    }
    

    Also note that visibleItemsInfo returns also the partially visible items.