I have a `LazyColumn` that displays a `mutableStat...
# compose
c
I have a
LazyColumn
that displays a
mutableStateListOf(items)
. There are about 100 items in the list and once populated (loaded from a server) the list doesn't change. Individual items do sometimes mutate however (by making a mutated copy of the item and replacing the previous instance of it in the list). This all works as expected. I now want to add a search/filter TextField, that reduces the items displayed to just those where
item.name.contains(searchText)
. I'm not sure what the best approach to implementing this is: 1. Create a new
mutableStateListOf()
list that contains just the filtered items, clearing and repopulating it from the full list each time the search text changes. It seems tricky to deal with mutating items using this approach though (both lists will need updating). 2. Similar to 1, but convert to a
mutableStateOf(List<Item>)
and create a new list (from the separate full list) each time the search text changes or an item is mutated. 3. Leave things as they are, but make the item @Composable take the search text as a parameter, and display nothing if
contains()
returns false. This seems easy, but also hacky. 4. Something else?
Note that the search/filtering is purely a UI thing, whereas the item mutation can be driven from both the UI or pushed out from the server.
t
I solved this with
derivedStateOf
Copy code
private val myList = mutableStateListOf(items)
val filteredList by derivedStateOf {
    if (shouldApplyFilter) {
        myList.filter {
            it.id < 3
        }
    } else {
        myList
    }
}
This way you only have to update your original list and have your filtered list be always up to date.
👍🏽 1
👍🏻 1
c
Ah brilliant, thank you! I figured I was missing something like this
👍 1
313 Views