Sam
08/19/2021, 8:42 PMkeys
to avoid recomposition of previously composed ones but can't seem to get it to work. Displaying a list with items and a button to shuffle the list item but all items are composed again (logging via SideEffect
)Sam
08/19/2021, 8:43 PMdata class Movie(val id: String, val title: String)
@Composable
fun MovieList() {
var movies by rememberSaveable {
mutableStateOf(List(100) {
Movie("$it", "Movie $it")
})
}
Column {
Button(
onClick = { movies = movies.shuffled() }
) {
Text(text = "Shuffle Movies")
}
LazyColumn {
items(movies) { movie ->
key(movie.id) {
MovieListItem(movie)
}
}
}
}
}
@Composable
fun MovieListItem(movie: Movie) {
Text(text = movie.title)
SideEffect {
Log.e(TAG, "MovieListItem composed for $movie")
}
}
Ian Lake
08/19/2021, 8:55 PMkey
parameter on items
? https://developer.android.com/reference/kotlin/androidx/compose/foundation/lazy/package-summary#(androidx.compose.founda[…]nction1,kotlin.Function2)Sam
08/19/2021, 8:59 PMLazyColumn {
items(movies, key = { it.id } ) { movie ->
MovieListItem(movie)
}
}
Zach Klippenstein (he/him) [MOD]
08/19/2021, 9:05 PMkey
or the key parameter is for anyway.Sam
08/19/2021, 9:07 PMSam
08/19/2021, 9:07 PMKey Point: Use the key composable to help Compose identify composable instances in Composition. It's important when multiple composables are called from the same call site and contain side-effects or internal state.
Zach Klippenstein (he/him) [MOD]
08/19/2021, 9:09 PMSam
08/19/2021, 9:11 PMinstances haven't changed, and can reuse them
. What is being reused?Sam
08/19/2021, 9:21 PMZach Klippenstein (he/him) [MOD]
08/19/2021, 9:26 PMZach Klippenstein (he/him) [MOD]
08/19/2021, 9:29 PMSam
08/19/2021, 9:29 PMSam
08/19/2021, 9:30 PMequals
by default to identify them than having devs provide a key?Sam
08/19/2021, 9:34 PMZach Klippenstein (he/him) [MOD]
08/19/2021, 9:34 PMZach Klippenstein (he/him) [MOD]
08/19/2021, 9:35 PMSam
08/19/2021, 9:36 PMZach Klippenstein (he/him) [MOD]
08/19/2021, 9:46 PMSam
08/19/2021, 9:48 PMid
& title
in this caseSam
08/19/2021, 9:49 PMhashCode
of the state and use that as an identifier. But this can work only if there is a unique identifier within the data setZach Klippenstein (he/him) [MOD]
08/19/2021, 9:55 PMSam
08/19/2021, 9:58 PM