Chris Fillmore
05/17/2022, 2:31 PMderivedStateOf
? (In a VM)Chris Fillmore
05/17/2022, 2:32 PMclass MyViewModel : ViewModel() {
val myStateFlow = MutableStateFlow(...)
val myDerivedState = derivedStateOf {
// I would like to use the value of myStateFlow here
}
}
Chris Fillmore
05/17/2022, 2:33 PM@Composable
I could collectAsState… but I’m not sure what to do outside that contextChris Fillmore
05/17/2022, 2:33 PMmyanmarking
05/17/2022, 2:52 PMval state by remember(viewModel){…collectAsState() }
derivedStateOf { state.sth }
Chris Fillmore
05/17/2022, 2:53 PMnatario1
05/17/2022, 2:54 PMChris Fillmore
05/17/2022, 2:55 PMChris Fillmore
05/17/2022, 2:55 PMmyanmarking
05/17/2022, 2:55 PMChris Fillmore
05/17/2022, 2:57 PMStateFlow
. Is there a reason you suggest I shouldn’t use derivedStateOf in a VM?myanmarking
05/17/2022, 2:59 PMChris Fillmore
05/17/2022, 3:03 PMState
is part of compose runtime
, so I don’t see it makes a difference whether I have a dependency on the compose runtime vs coroutines/flow. I would argue you should use whatever satisfies your use case. But I’d be open to hearing arguments otherwise.natario1
05/17/2022, 3:05 PMmyanmarking
05/17/2022, 3:26 PMZach Klippenstein (he/him) [MOD]
05/17/2022, 11:05 PMChris Fillmore
05/18/2022, 12:10 AMTash
05/18/2022, 1:52 AMclass MyViewModel : ViewModel() {
val myState = mutableStateOf(...)
val myDerivedState = derivedStateOf {
// Some function of myState...
}
...
// Set myState.value in the same place you updated StateFlow
}
This is the only way I can think of if you really want to expose Snapshot state, because otherwise, there is no way to cross the StateFlow
/Snapshot state boundary from a non-Compose context such as VMZach Klippenstein (he/him) [MOD]
05/18/2022, 3:18 AMif I need effects via onEach in non-compose contextTriggering effects on state change is always risky, since states can be conflated with both approaches. But just as you can go from a
StateFlow
to a State
via collectAsState
, you can always go from a State
to a Flow
with snapshotFlow
.Chris Fillmore
05/18/2022, 11:11 PM