I noticed that two of my screens had a lot of dupl...
# compose
p
I noticed that two of my screens had a lot of duplicated functions and some duplicated vals inside my uistate, because both screens have a map with bookmark pois etc..., so I extracted all the duplicated functions to a parent viewmodel class and all the duplicated vals to a parent uistate class. Now the parent viewmodel is called MapViewModel and these uistate vals that were used only by this parent are stored in a MapState stateflow used by this parent. Now I'm using hierarchy for my two screens, both extends this MapViewModel and both have now two stateflow vals, one for the UiState and one for the MapState, which is inherited from his parent (I made protected the private
_mapState
val to be able to access it on the childrens). Is this correct? is a good practice to have two UiState stateflows and access both of them on my screen with this?
Copy code
val uiState by vm.uiState.collectAsStateWithLifecycle()
val mapState by vm.mapState.collectAsStateWithLifecycle()
d
Define correct is the usual answer 😄 If it makes sense for your project to have them separate there's nothing wrong with it really. If you'd rather have one state val you can use combine to achieve that.
p
With correct I mean following good practices and patterns. how can I mix this with combine in a appropiate way? child:
Copy code
data class LinesScreenUiState(
    val loading: Boolean = false,
    val lines: List<Line> = emptyList(),
    val selectedLine: Line? = null
)
private val _uiState = MutableStateFlow<LinesScreenUiState>(LinesScreenUiState(loading = true, lines = emptyList()))
val uiState: StateFlow<LinesScreenUiState> = _uiState
parent:
Copy code
data class MapState(
    val hasLocationPermission: Boolean = false,
    val userLocation: LatLng? = null,
    val lineSteps: List<Step> = emptyList()
)
protected val _mapState = MutableStateFlow(MapState())
val mapState: StateFlow<MapState> = _mapState
d
Well that's the thing - "appropriate" is whatever works for your code/app as I mentioned. Using https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/combine.html you can get 1 StateFlow, how exactly you combine your 2 data classes into 1 new data class is the part that you'll have to decide on your own. You could just add a wrapper data class that holds both. But then again, you have to ask yourself what are you trying to achieve - there isn't a particular reason why you have to combine the 2 states, if it makes sense to have 2 just have 2.