https://kotlinlang.org logo
#flow
Title
# flow
h

Hank

09/24/2021, 2:03 AM
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

baxter

09/24/2021, 4:41 AM
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

Todd

09/24/2021, 6:04 PM
In addition to Pablo’s great answer, the kotlin documentation on this is very good: SharedFlow StateFlow
h

Hank

09/25/2021, 12:13 AM
Thanks for answering. It's easy to understand.😀
2 Views