Bradleycorn
12/24/2020, 4:17 PMderivedStateOf
and wondering if there is any difference between the following 2 examples? Is one approach "better" than the other? Are there problems with one approach or the other? Is there an advantage to one over the other (other than just the amount of code)? Is example 2 a proper use of derivedStateOf
? Am I likely to run into concurrency issues?
EXAMPLE 1
var UiState by mutableStateOf(MyCompositeDataClass(value1 = null, value2 = null))
private set
init {
viewModelScope.launch {
getValue1Flow().collect { UiState = UiState.copy(value1 = it) }
}
viewModelScope.launch {
getValue2Flow().collect { UiState = UiState.copy(value2 = it) }
}
}
EXAMPLE 2
private var state1 by mutableStateOf<String?>(null)
private var state2 by mutableStateOf<String?>(null)
val UiState by derivedStateOf {
UiState(value1 = state1, value2 = state2)
}
init {
viewModelScope.launch {
getValue1Flow().collect { state1 = it }
}
viewModelScope.launch {
getValue2Flow().collect { state2 = it }
}
}
Adam Powell
12/24/2020, 4:36 PMAdam Powell
12/24/2020, 4:37 PMstate1
and state2
or if other derived states mashed up other sets of them; otherwise it sets up quite a bit of machinery and brings additional state vars into scope that aren't really necessary and are kind of noisyAdam Powell
12/24/2020, 4:38 PM.combine
operator to merge the flows and keep only one launched coroutine modifying `uiState`; with viewModelScope
you can get away with it the way it's written above since it's a single-threaded dispatcher, but it's kind of a janky habit to get intoBradleycorn
12/24/2020, 5:30 PMstate
objects (Ex 2) is just more moving parts to maintain.Adam Powell
12/24/2020, 5:33 PM