Sobes.tech
Middle+

What is SharedFlow and how does it differ from StateFlow?

sobes.tech AI

Answer from AI

SharedFlow is a data stream from coroutines that broadcasts values to multiple subscribers (a "hot" stream).

StateFlow is a variation of SharedFlow that represents a state stream. It always has an initial value and emits the last known value to new subscribers.

Main differences:

Characteristic SharedFlow StateFlow
Initial value None by default, can be set with replay Always has a mandatory initial value
Replaying values for new subscribers Managed by the replay parameter Always replays the last value
Buffer size Buffer size set by extraBufferCapacity Buffer size is 0 (except for the last value)
Emission of identical values Emits all values, even if they are identical Does not emit consecutive identical values (if they are equal by .equals())
Use case Events, data streams UI states or other current states