StateFlow vs Flow

What’s the point using StateFlow / MutableStateFlow with Compose when you can use simple Flow and observe it with collectAsState / collectAsStateWithLifecycle? Default value and a setter? But actually, it’s convenient - no need to parse flows manually.

Answering both this topic and also another one: MutableStateFlow for methods (or how to make an observable function)? - #10 by Psijic I think there are some misconceptions here.

If you want to find the value of something at the time you need it, then you don’t need flows - a regular function or property provides you that. If you want to observe some value for changes and be notified, then this is really a pain with functions/properties - then we use flows. But because flow doesn’t represent just a simple value, but is a… well, flow of data, stream of events, potentially infinite, its API is much more complicated. We don’t get its data just like that, we observe it for changes. Also, flow doesn’t have a concept of “current value”, because it is a highway with data.

StateFlow is somewhere in between. It is still a flow, but it remembers its last/current item, so you can fetch it at any time, without waiting. And you can still observe it for changes, as any other flow. On the other hand, regular flows are good, because they are cold. That means they work on-demand, they provide items only if you actively observe them, they are tight to the lifecycle of the consumer. StateFlow can’t be cold, because it has to exist and do something even if you don’t actively read from it - so it can provide you the last value at any time. Therefore, it may require some additional maintenance, for example a coroutine that runs it all the time.

Summarizing: use proper tools for your specific needs. If you only need to get the value at a specific point in time, you don’t need flows. If you need to observe some value for changes, but you don’t need to get the value at a specific point in time, you don’t need StateFlow, but regular flow is enough. If you use a flow for collectAsState() only, then you don’t benefit from using StateFlow.

2 Likes

That’s good explanation. Android had liveData before - it’s cold enough, can be observed and changed its data everywhere with observeForever without a coroutine. Could you provide a sample code how to do it with StateFlow?