vide
05/17/2023, 8:25 PMState
and derivedStateOf
, since combine
is somewhat clumsy to use, and flow operators lose the stateful type (StateFlow<T>.map(): Flow<T>
). Is this a bad idea for some reason? It would also avoid having to have a wrapper composable just to collect flows to state. I got the idea for this from a comment in GitHub by Adam Powell. Example in š§µfun <T> StateFlow<T>.collectAsState2(scope: CoroutineScope): State<T> {
val state = mutableStateOf(value)
scope.launch {
collect { state.value = it }
}
return state
}
interface IStateHolder {
val uiState: UiState
}
class State(dataSource1: DataSource1, dataSource2: DataSource2, scope: CoroutineScope) : IStateHolder {
private val dataSource1State = dataSource1.data1Flow.collectAsState2(scope)
private val dataSource2State = dataSource2.data2Flow.collectAsState2(scope)
override val uiState = derivedStateOf {
if (dataSource1State.value == ...) {
// Construct an UiState here based on complex logic
}
}
companion object {
@Composable
fun rememberState(dataSource1: DataSource1, dataSource2: DataSource2): IStateHolder {
val scope = rememberCoroutineScope()
return remember { State(scope) }
}
}
}
myanmarking
05/17/2023, 8:49 PMvide
05/17/2023, 8:56 PMcollectAsState2
is not a composable function and isn't called from any composable contextState
is created with rememberState()
, so it's not recreated on every recomposition, only during the initial compositionmyanmarking
05/17/2023, 9:11 PMvide
05/17/2023, 9:56 PMFlow
which leaves the question of what to initialize the state with, as there is no current value guaranteed. I could always initialize with nulls, but it feels a little counterproductive when all my data sources are StateFlows
and have a non-null value availableIan Lake
05/18/2023, 5:57 AMwhen all my data sources areStateFlows
This feels very odd. All of your data sources are hot and have an always up to date value (that's what a StateFlow means)? That feels like a terribly inappropriate use of resources or a misuse of StateFlow. That's why data sources expose Flows, not StateFlows
vide
05/18/2023, 6:41 AM