Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MutableStateFlow not firing when add item with ViewModel

I need to observe/collect data from Stateflow inside ViewModel when the add method is called. But when I add an item, the state doesn’t do recomposition.

This is my ViewModel code:

private var _selectedData = MutableStateFlow<MutableList<String>>(mutableListOf())
val data = listOf("Hello", "my", "name", "is", "Claire", "and", "I", "love", "programming")
val selectedData = _selectedData.asStateFlow()
    
fun addSelectedData(index: Int){
    _selectedData.value.add(data[index])
    Log.d("TAG", _selectedData.value.toString())
} 

And this is my composable code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

val mainViewModel: MainViewModel = viewModel()
val selectedData by mainViewModel.selectedData.collectAsState()
LaunchedEffect(key1 = selectedData){
    Log.d("TAG", "SELECTED $selectedData")
}

Thanks in advance.

>Solution :

MutableStateFlow is not able to notice that you modified the object that it holds. You have to set a new object to MutableStateFlow, so a new list.

Change the type of _selectedData to MutableStateFlow<List<String>> and then do:

_selectedData.value = _selectedData.value + data[index]

You can make it shorter with:

_selectedData.value += data[index]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading