Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 467
Remo Avatar asked Dec 14 '22 07:12

Remo


1 Answers

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())
like image 173
Gabriele Mariotti Avatar answered Dec 24 '22 14:12

Gabriele Mariotti