Lately, we have a new API since android lifecycle library version 2.6.0-alpha01, i.e.
collectAsStateWithLifecycle(...)
It is advocated by Google Developer in this article
If you’re building an Android app with Jetpack Compose, use the
collectAsStateWithLifecycle
composable function (instead ofcollectAsState
)
I try it out, for flow (cold flow) e.g.
val counter = flow {
var value = 0
while (true) {
emit(value++)
delay(1000)
}
}
It is useful to have
flow.collectAsStateWithLifecycle(0)
But if we have a hot flow like mutableStateFlow
val stateFlow = MutableStateFlow(0)
It seems useless to have
stateFlow.collectAsStateWithLifecycle(0)
given that it doesn't block any emission.
Am I right to state collectAsStateWithLifecycle
only useful for cold flow, but not hot flow?
If I am wrong, can you show me an example where collectAsStateWithLifecycle
is useful for hot flow too?