Qamar Khan
08/17/2024, 11:36 PMprivate val _uiState = MutableStateFlow(ActivateTagUiState())
val uiState: StateFlow<ActivateTagUiState> = _uiState.asStateFlow()
Ui class:
data class ActivateTagUiState(
val isLoading: Boolean = false,
val propertyA: String = ""
so on...
)
that,s how i am updating values
private fun updateLoadingState(isLoading: Boolean) {
_uiState.update {
it.copy(isLoading = isLoading)
}
or another way is
_uiState.value = uistate.value.copy{isLoading = isLoading}
}
val uiState by viewModel.uiState.collectAsState()
The copy
function itself creates a new instance of a class, which means any change in properties will be observed using MutableStateFlow
, leading to the entire screen being recomposed. How can we avoid unnecessary recompositions?
In general, my point is that if we have 10 properties, all linked to UI components, why should all of them be recomposed again even if only a single property is changed or updated?
#flow #compose-androidPablichjenkov
08/18/2024, 1:05 AMLoading(): ActiveTagUiState
rather than a property. Why?
In general that's the way compose rolls. When you update the root state unfortunately the whole screen will refresh, but you can help with that refresh in two ways.
1- Using stable classes in the data or enabling strong skipping. This tells a Composable function to skip composition if the state data is the same.
2- Design the Composable UI in a way that it can isolate the compositions to the part of the screen that needs the composition. This is where my initial suggestion takes place. Instead of having a full ViewState class holding so many parameters that can trigger recomposition, better group them to the stage in the view where they belong. Sealed classes help in this case