Hi there. Given that I have a `LazyList` with item...
# compose
s
Hi there. Given that I have a
LazyList
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!
Copy code
@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}"
}
This is the behaviour I want to avoid, when scrolling back up - I would like to have the results immediately seen. But I have the feeling, some outer data holder like a ViewModel will be needed:
z
Yea I don't think there's anything compose specific about this, sounds like you're just looking for a regular old cache.
s
Thanks, appreciate it. That’s the feeling I have as well 😄