5

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 of collectAsState )

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?

Elye
  • 53,639
  • 54
  • 212
  • 474

1 Answers1

9

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.

Stylianos Gakis
  • 862
  • 8
  • 19
  • 2
    Nice! Thanks that's great. I got the answer from the Author too https://twitter.com/manuelvicnt/status/1587006978076938240 – Elye Oct 31 '22 at 10:28