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?
CodePudding user response:
It is useful for any case where the flow relies on there being consumers for it to be hot.
In the case where you just do val stateFlow = MutableStateFlow(0)
as you say, it would not change anything, no.
However one "hot flow" case where it matters, is where the flow becomes hot using the stateIn function, using the WhileSubscribed policy as the SharingStarted parameter of stateIn
. Subscribing using collectAsStateWithLifecycle
in that case means that the flow will not have a subscriber when the lifecycle is not at least STARTED or whatever you pass to minActiveState
.