how to change value of a mutable state and use it in other fragment

Viewed 21

I'm trying to add some filtering functionality to my app, so I decided to take the filters from the user via some checkboxes and save the filters in mutable live data, finally use it in list fragment

every thing is fine except at the moment I leave the filter fragment the mutable live data changes to first state of it self

here is the mutable state value implementation inside view model class

val filterByGenreInfo1LiveData = MutableStateFlow(
    FilterByGenreInfo1(
        genres = setOf("Crime","Drama","Action","Biography","History","Adventure","Fantasy","Western","Comedy","Sci-Fi",
            "Mystery","Thriller","Family","War","Animation","Romance","Horror","Music","Film-Noir","Musical","Sport"),
        selectedGenres = emptySet()
    )
)

and here is the recyclerview implementation

private fun onGenreFilterClick1(selectedFilter : String){
    viewModel.viewModelScope.launch {
        val currentSelectedFilter = viewModel.filterByGenreInfo1LiveData.value

            val newFilter =  currentSelectedFilter.copy(
                selectedGenres = if(currentSelectedFilter.selectedGenres.contains(selectedFilter)){
                    currentSelectedFilter.selectedGenres.filter { it != selectedFilter }.toSet()
                }else{
                    currentSelectedFilter.selectedGenres + setOf(selectedFilter)
                }
            )

            viewModel.filterByGenreInfo1LiveData.value = newFilter

    }
}
0 Answers
Related