Hi guys, can anyone tell me what's the difference ...
# flow
h
Hi guys, can anyone tell me what's the difference between sharedflow and statedflow? I read the post on Android Developer but still didn't get it.
b
Both are
SharedFlow
types, meaning they can have multiple subscribers for the same stream, and never complete. A
SharedFlow
can emit a history of events that were emitted previously. This would be helpful for situations where you are drawing a route on a map, and need all the previous points plus any new points coming in, to continue extending the drawn route. SharedFlows typically require a coroutine to update events, and can have a buffer to handle backpressure, or suspend if there is none. However, a
StateFlow
is special in that it will only ever emit the latest item in the stream. An example usage for the state flow is keeping track of the current lifecycle state of an Android Activity. Any subscriber to this flow would get the current state (ex. "onResumeState"), and any updates to the flow. It would never emit anything from the past. On top of that,
StateFlow
has no backpressure and also has functions that allow for setting the state atomically and in a thread-safe manner, meaning you can set it without the need of a coroutine.
👍 6
t
In addition to Pablo’s great answer, the kotlin documentation on this is very good: SharedFlow StateFlow
h
Thanks for answering. It's easy to understand.😀