handle UI State with Stateflow and ViewModel in Jetpack Compose

57 Views Asked by At

as it is recomended in lots of documents and tutorials we should define ui states as varaiables of a data class and define it as a MutableStateFlow in our viewModel and whenever we want to update the screen whith new state we should update the MutableStateFlow with that data class.

for exmple :

data class UiState( val isLoading : Boolean = false , val moviesList : List<Movie> = emptyList(), val listTitle : String = "popular")

in viewModel :

var uiState = MutableStateFlow(UiState()) private set

and for updating : uiState.update {it.copy(isLoading = true)}

now here is the question : i'm wondering that isn't it a bad practice to copy the data class whenever we want to update the state and Update just one property, leave the rest as they were . imagine a complicated screen that has ten states and we are creating a new instance of data class just for updating one of its property each time . as each copy instantiate a new instance, doesn't this cause some memory leak issue ?

isn't it better to provide a separate stateFlow for each state and each time we just update that state instead of making a new instance of a data class by copying that.

var titleState = MutableStateFlow("popular") private set

var movieListState = MutableStateFlow<List<Movie>>(emptyList<Movie>()) private set

var isLoadingState = MutableStateFlow(false) private set

and for updating just call :

titleState.value = "upComing"

0

There are 0 best solutions below