a coworker submitted the following code in a PR, w...
# compose
n
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?
❤️ 1
s
The answer is in the implementation https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:lifecycle/lifecycle-runtime-compose/src/commonMain/kotlin/androidx/lifecycle/compose/FlowExt.kt;l=59?q=Collectasstatewithlifecycle It will use whatever the composition local is from wherever the call-site is. If you're using androidx.navigation this is typically the BackStackEntry's lifecycle since it is a lifecycle owner itself and each backstack entry sets up this local itself.
👍 1
🌟 1
z
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?
n
i agree