Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LazyColumn and mutable list - how to update?

I'm new to Jetpack Compose and I've spent some hours to find how to make a LazyColumn update what I update my list. I've read that it needs to be a immutable list to update LazyColumn, but I can't seem to get it to work.

The code looks like:

@Composable
fun CreateList() {
    var myList : List<DailyItem> by remember { mutableStateOf(listOf())}
    
    myList = getDailyItemList() // Returns a List<DailyItem> with latest values and uses mutable list internally
    
    // Function to refresh the list
    val onUpdateClick = {
        // Do something that updates the list
        ...
        // Get the updated list to trigger a recompose
        myList = getDailyItemList()
    }
    // Create the lazy column
    ...
}

I have tried several things and either is the list never updated when tapping the update button or only the first item is updated but not the rest of the items in the list. I looked in the documentation and there it says this, but I don't understand it:

Instead of using non-observable mutable objects, we recommend you use an observable data holder such as State<List> and the immutable listOf().

How to update the list so the LazyColumn is updated?

like image 401
Mackan Avatar asked Sep 12 '25 17:09

Mackan


1 Answers

Use SnapshotStateList, the list is mutable. Any modification (add, remove, clear, ...) to the list will trigger an update in LazyColumn.

Similar to mutableListOf() (for MutableList) there is mutableStateListOf() to create a SnapshotStateList.

Extention function swapList() just combines clear() and addAll() calls to replace old list with new list.

fun <T> SnapshotStateList<T>.swapList(newList: List<T>){
    clear()
    addAll(newList)
}

@Composable
fun CreateList() {
    val myList = remember { mutableStateListOf<DailyItem>() }
    
    myList.swapList(getDailyItemList()) // Returns a List<DailyItem> with latest values and uses mutable list internally

    // Function to refresh the list
    val onUpdateClick = {
        // Do something that updates the list
        ...
        // Get the updated list to trigger a recompose
        myList.swapList(getDailyItemList())
    }
    // Create the lazy column
    ...
}
like image 86
Om Kumar Avatar answered Sep 15 '25 20:09

Om Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!