Home > Mobile >  MutableStateFlow not firing when add item with ViewModel
MutableStateFlow not firing when add item with ViewModel

Time:03-24

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:

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

Thanks in advance.

CodePudding user response:

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]
  • Related