Is there any difference between usage of remember below ? ```@Composable fun ClubItem(club: Club, ...
s
Is there any difference between usage of remember below ?
Copy code
@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)) }
}
a
what behavior are you looking to achieve?
both of these snippets look suspicious and neither will do what you probably intend
The first will create a
derivedStateOf
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.
That it's a
derivedStateOf
means that if that initial list happens to be a
mutableStateListOf
that changes over time,
isSelected
will update in response.
👍 1
The second also has the same problem where different list instances of
selectedClubs
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.
Overall,
remember
,
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.
I suspect that what you want is probably:
Copy code
val 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:
Copy code
val isSelected = club in selectedClubs
if you aren't.
s
Thanks for your detail answers, I'm using ClubItem in LazyClomn where each item can be selected and unselected and I'm maintaining this selected item in shared Preference like this val selectedClubs = facrViewModel.savedClubs.collectAsState(initial = emptyList())
I initially tried to do something like this but it doesn't work.
Copy code
@Composable
fun ClubItem(club: Club,
             isSelected: Boolean,
             onItemClicked: (Club) -> Unit) {
   }