Shakil Karim
03/13/2021, 4:07 PM@Composable
fun ClubItem(club: Club,
selectedClubs: List<Club> = emptyList(),
onItemClicked: (Club) -> Unit) {
val isSelected by remember { derivedStateOf { selectedClubs.contains(club) } }
}
@Composable
fun ClubItem(club: Club,
selectedClubs: List<Club> = emptyList(),
onItemClicked: (Club) -> Unit) {
val isSelected by remember { mutableStateOf(selectedClubs.contains(club)) }
}
Adam Powell
03/13/2021, 4:13 PMAdam Powell
03/13/2021, 4:14 PMAdam Powell
03/13/2021, 4:15 PMderivedStateOf
from the first value of selectedClubs
the call to ClubItem
is composed with and remember it, and if the selectedClubs
list instance changes in a future recomposition, isSelected
will always refer to the original list.Adam Powell
03/13/2021, 4:16 PMderivedStateOf
means that if that initial list happens to be a mutableStateListOf
that changes over time, isSelected
will update in response.Adam Powell
03/13/2021, 4:18 PMselectedClubs
will never update isSelected
in a recomposition, since the initial composition instance is captured in the remember
expression. val foo by remember { mutableStateOf(...) }
should probably be a lint error.Adam Powell
03/13/2021, 4:20 PMremember
, DisposableEffect
and LaunchedEffect
can all result in lambda captures living longer than you expect and values going stale when you may or may not intend it.Adam Powell
03/13/2021, 4:22 PMval isSelected by rememberUpdatedState(club in selectedClubs)
if you're using isSelected
in other observing or long-lived lambda captures later in the composable, or perhaps more simply:
val isSelected = club in selectedClubs
if you aren't.Shakil Karim
03/13/2021, 4:39 PMShakil Karim
03/13/2021, 4:41 PM@Composable
fun ClubItem(club: Club,
isSelected: Boolean,
onItemClicked: (Club) -> Unit) {
}