Daniel Rendox
08/20/2023, 10:23 AMderivedStateOf
?
@Composable
fun TodoList(highPriorityKeywords: List<String> = listOf("Review", "Unblock", "Compose")) {
val todoTasks = remember { mutableStateListOf<String>() }
val highPriorityTasks by remember(highPriorityKeywords) {
derivedStateOf {
todoTasks.filter { task ->
highPriorityKeywords.any { keyword ->
task.contains(keyword)
}
}
}
}
// ...The UI
Box(Modifier.fillMaxSize()) {
LazyColumn {
items(highPriorityTasks) { /* ... */ }
items(todoTasks) { /* ... */ }
}
/* Rest of the UI where users can add elements to the list */
}
}
The idea is to recompose only when todoTasks
or highPriorityKeywords
change. Questions:
1. Why does the remember
function accept keys here, if the derivedStateOf
will update automatically whenever one of the states changes? And it only accepts one — highPriorityKeywords
, why do then we not pass todoTasks
as well?
2. How would the usage of derivedStateOf
instead of remember(todoTasks, highPriorityKeywords)
optimize the performance? Wouldn't these two things do the same stuff in this particular example?
I understand the difference between remember+keys
and remember+derivedStateOf
. But in this example we use remember+keys+derivedStateOf
, which really bothers me.Stylianos Gakis
08/20/2023, 10:48 AMStylianos Gakis
08/20/2023, 10:49 AMremember + keys + derivedStateOf
is in fact necessary if you're planning to create a new state coming from a mix of other state objects, and other non-state objects (which derivedStateOf wouldn't know how to observe like it does state objects)Daniel Rendox
08/20/2023, 11:18 AMval highPriorityTasks = remember(todoTasks, highPriorityKeywords) {
todoTasks.filter { task ->
highPriorityKeywords.any { keyword ->
task.contains(keyword)
}
}
}
And then, for example, add 10 tasks that do not contain high priority keywords, we will end up with 10 unnecessary recompositions that could be avoided using derivedStateOf
.
And we use highPriorityKeywords
as a key simply because its not a state.
Thank you, @Stylianos Gakis!Erfannj En
08/20/2023, 1:25 PMStylianos Gakis
08/20/2023, 1:32 PMromainguy
08/20/2023, 3:55 PMromainguy
08/20/2023, 3:55 PMromainguy
08/20/2023, 3:55 PMStylianos Gakis
08/20/2023, 4:08 PMromainguy
08/20/2023, 4:11 PMromainguy
08/20/2023, 4:13 PMromainguy
08/20/2023, 4:13 PMStylianos Gakis
08/20/2023, 4:14 PMStylianos Gakis
08/20/2023, 4:17 PMromainguy
08/20/2023, 4:27 PMromainguy
08/20/2023, 4:27 PMErfannj En
08/20/2023, 4:28 PMromainguy
08/20/2023, 4:28 PM