Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jetpack compose stateflow not refreshing list

In my project, I have two fragments.

One is a normal fragment, and another is a bottomSheetDialogFragment.

In my normal fragment, I have a lazyColumn.

I would like to do some settings in the bottomSheetDialogFragment and create a new Hiit object and put it into my hiitItems list in my viewmodel.

The problem is that since my normal fragment is partially covered by the bottomSheetDialogFragment, jetpack compose won't re-compose when my list changes.

So I decided to turn to stateFlow given that it is always firing, and I assume this might cause recomposition. But unfortunately, it did not.

Below are my codes:

// in my viewmodel
// using stateflow to hold the list of hiitItems 
    private var _hiitItems = MutableStateFlow(mutableListOf(HiitItem()))
    val hiitItems = _hiitItems

In my normal fragment, I'm using composeView to take advantage of jetpack compose:

 setContent {

// get hiitItems
val hiitItems by vm.hiitItems.collectAsState()
...

 // lazyColumn
LazyColumn(modifier = Modifier.fillMaxSize()) {
    items(hiitItems) // I'm assuming auto refreshing the list here
    {
     ItemCard(item = it) // ItemCard is just an ordinary composable
    }
 }
}

In my bottomSheetDialogFragment, I have a button, whose function is to add the newly created hiitItem into my hiitItems list, and cause recomposition:

 hiitItems.add(newItem)

Any idea why the change in my hiitItems list is not causing recomposition after I dismiss my bottomSheetDialogFragment?

like image 396
Fever Avatar asked Mar 20 '26 01:03

Fever


1 Answers

Your mutableStateFlow is not firing because you are mutating the list. Instead of adding an item to the list (mutating it) make a new list with the new item and update your flow with it.

private var _hiitItems = MutableStateFlow(emptyList<HittItem>())

and later

_hiitItems.value = _hiitItems.value + newItem
like image 110
Francesc Avatar answered Mar 23 '26 00:03

Francesc



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!