Search code examples
androidkotlinlistviewandroid-jetpack-compose

Jetpack Compose: Update composable when list changes


I've got a composable on a Screen which shows a list of Track items (favourites) :

var favourites: MutableList<Track> by mutableStateOf(mutableListOf())
@ExperimentalFoundationApi
@Composable
private fun ResultList(model: FreezerModel) {
    with(model) {
        if (favourites.isEmpty()) NoDataMessage("No favourites yet")
        else {
            LazyColumn(state = rememberLazyListState()) {
                items(favourites) {
                    TrackCard(it, model)
                }
            }
        }
    }
}

On click events, I am updating my favourites list (add/remove item). How can I make my composable reflect these changes immediately (like to re-draw itself or something similar)? So far, it only works when I first switch to another screen.

Thanks for your inputs!


Solution

  • You need to use a MutableStateList<T> so that Compose can automatically recompose when the state changes.

    From official doc:

    Caution: Using mutable objects such as ArrayList<T> or mutableListOf() as state in Compose will cause your users to see incorrect or stale data in your app.

    In your code use

    val favourites = remember { mutableStateListOf<Track>()}
    

    instead of

    var favourites: MutableList<Track> by mutableStateOf(mutableListOf())