Steffen Funke
10/29/2021, 7:40 AMLazyList
with items, and each item performs an expensive calculation for itself (Think of very item constrained data, like loading an image, …).
At the moment, as I scroll down and back up the list, the calculation is re-executed, as the item enters composition. This makes sense, but is not quite what I would like to achieve. Instead, I imagined some kind of LazyList
built-in caching mechanism - since the input parameters of the items are known and not changed, and the calculation has already taken place once.
So my questions are:
• is there any way to “cache” such calculations over item compositions in a LazyList
, to avoid a re-calculation on item appearance?
• I wrapped the calculation in a LaunchedEffect
keyed by the input, but it does run every time item enters composition. Makes sense, but not sure if there is a better way?
• Or is this totally wrong think, and I should implement this caching myself, e.g. with a ViewModel type of data holder?
Some sample code, hope it makes sense 👉
Thanks!Steffen Funke
10/29/2021, 7:41 AM@Composable
fun LongRunningOperationDemo() {
...
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(items) { index ->
MyListItem(index)
Divider()
}
}
...
}
@Composable
fun MyListItem(index: Int) {
// initial value
var calculationResult by remember { mutableStateOf("LOADING") }
// Launchedeffect to trigger expensive calculation
// can this be cached, based on the key?
LaunchedEffect(key1 = index) {
calculationResult = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
expensiveCalculation(index)
}
}
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
Text(text = "Item $index")
// Displaying of Result
Text(text = calculationResult)
}
}
private fun expensiveCalculation(index: Int): String {
Thread.sleep(1000)
return "✅ Calculated Result for Item ${index}"
}
Steffen Funke
10/29/2021, 7:45 AMZach Klippenstein (he/him) [MOD]
11/01/2021, 4:58 PMSteffen Funke
11/02/2021, 6:30 AM