1

Each time the TopAppBar collapses and expands, all of the LazyColumn elements are recomposed multiple times.

@OptIn(ExperimentalMaterial3Api::class, ExperimentalAnimationApi::class)
@Composable
fun RoomsScreen(
     viewModel: ScreenViewModel = hiltViewModel()
) {

     val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior(rememberTopAppBarState())

     scaffold(
         modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
         topBar = {
             TopAppBar(
                 scrollBehavior = scrollBehavior
                 ...
             )
         },
     ) { paddingModifier ->

         LazyColumn(
             modifier = Modifier
                 .padding(paddingModifier)
                 .fillMaxSize()
             ,
         ) {
             items(viewModel.list.size) { index ->
                 RoomCard(
                     viewModel = viewModel.list[index],
                 )
             }
         }

     }

}

It is clear that when collapsing and expanding TopAppBar, the paddingModifier changes, and the LazyColumn must be rebuilt, but it is not entirely clear why all nested elements should be rebuilt (hundreds of times while the movement takes place), this greatly squanders performance. What would you advise in this situation?

P.S: If you use pinnedScrollBehavior, of course, the problem disappears, but this is not what you want to get

Michael
  • 11
  • 2

1 Answers1

0

The Scaffold padding values can be declared as the contentPadding of the LazyColumn to avoid recomposition caused by the change of the padding values:

LazyColumn(
    modifier = Modifier.fillMaxSize(),
    contentPadding = paddingValues
) { ...

For the content you can add the list items directly instead of looping the list. Also, you can set a unique (different) key for each item, so if the items gets recomposed it won't trigger a recomposition of the remaining items. Here is an example:

items(
    items = viewModel.list,
    key = { "room_${it.id}" } // Set a unique key for each item
) { room ->

    RoomCard(room = room)

}

I highly suggest also to check out the Layout Inspector

Happy coding!