a coworker submitted the following code in a PR, with this code living inside an Android
ViewModel
Copy code
class SomeViewModel : ViewModel() {
private val state = MutableStateFlow(WelcomeState.Initial)
@Composable
fun collectState() = state.collectAsStateWithLifecycle().value
}
If this
collectState
function is called from another composable, what
lifecycle
will the
collectAsStateWithLifecycle
be referring to? The ViewModel lifecycle or the lifecycle from the calling composable?
This design smells weird to me. The confusion hints at the idea that this sort of helper method on the VM is an antipattern. If you’re trying to keep a clean separation between VM layer and view/compose layer, then keep compose things (like collectAsState) in the compose layer.
And if you’re not trying to keep that separation, then why use Flow at all instead of just storing the state in a snapshot state object?