Archie
08/08/2021, 1:59 PMderivedStateOf
.
In the official Documentation here: https://developer.android.com/jetpack/compose/side-effects
There is this sample code:
@Composable
fun TodoList(
highPriorityKeywords: List<String> = listOf("Review", "Unblock", "Compose")
) {
val todoTasks = remember { mutableStateListOf<String>() }
// Calculate high priority tasks only when the todoTasks or
// highPriorityKeywords change, not on every recomposition
val highPriorityTasks by remember(todoTasks, highPriorityKeywords) {
derivedStateOf {
todoTasks.filter { it.containsWord(highPriorityKeywords) }
}
}
Box(Modifier.fillMaxSize()) {
LazyColumn {
items(highPriorityTasks) { /* ... */ }
items(todoTasks) { /* ... */ }
}
/* Rest of the UI where users can add elements to the list */
}
}
Wouldn’t the same thing would be achieve even without the derivedStateOf
?
Like:
@Composable
fun TodoList(
highPriorityKeywords: List<String> = listOf("Review", "Unblock", "Compose")
) {
val todoTasks = remember { mutableStateListOf<String>() }
// Calculate high priority tasks only when the todoTasks or
// highPriorityKeywords change, not on every recomposition
val highPriorityTasks by remember(todoTasks.value, highPriorityKeywords) {
todoTasks.filter { it.containsWord(highPriorityKeywords) }
}
Box(Modifier.fillMaxSize()) {
LazyColumn {
items(highPriorityTasks) { /* ... */ }
items(todoTasks) { /* ... */ }
}
/* Rest of the UI where users can add elements to the list */
}
}
Wouldn’t this do the exact same thing?Dominaezzz
08/08/2021, 2:19 PMderivedStateOf
can potentially reduce the number of recompositions since it's value is calculated and subscribed to lazily.Archie
08/08/2021, 2:25 PMLazyColumn
but the second one, recomposes the whole TodoList(..)
composable right? Thats the main difference?Dominaezzz
08/08/2021, 2:26 PMArchie
08/08/2021, 2:31 PMval todoTasks = remember { mutableStateListOf<String>() }
updates its value, wouldn’t that recompose the whole TodoList(…)
anyway?Archie
08/08/2021, 2:33 PMderivedStateOf
converts it into a State<T>
.Dominaezzz
08/08/2021, 2:41 PMlhwdev
08/09/2021, 4:43 AMderivedStateOf
, isn't it sufficient to write val highPriorityTasks by remember { derivedStateOf { ... } }
as derivedStateOf
tracks its read by itself?mcpiroman
08/09/2021, 10:17 AMlhwdev
08/09/2021, 10:24 AMmutableStateOf
, can be used outside Composable.