LiveData or Flow(StateFlow/SharedFlow)?

LiveData or Flow(StateFlow/SharedFlow)?

UseCases of LiveData and Flow in Modern Android Development.

If get to know something new by reading my articles, don't forget to endorse me on LinkedIn

✅ LiveData is a lifecycle aware observable data holder (means it knows the lifecycle of the activity or a fragment) use it when you play with UI elements(views).

✅ Flow (cold stream) – In general think of it like a stream of data flowing in a pipe with both ends having a producer and consumer running on a coroutine.

✅ StateFlow(hot stream) does similar things like LiveData but it is made using flow by kotlin guys and only difference compare to LiveData is it’s not lifecycle aware but this is also been solved using repeatOnLifecycle api’s, so whatever LiveData can do StateFlow can do much better with power of flow’s api. StateFlow won’t emit same value.

✅ SharedFlow(hot stream) – name itself says it is shared, this flow can be shared by multiple consumers, I mean if multiple collect calls happening on the sharedflow there will be a single flow which will get shared across all the consumers, unlike normal flow.

✅ SharedFlow as a hot flow will emit data even if no one listening. Channel will hold data till someone consumes it. So if your view is not ready to receive an event and sharedFlow emits it, the event will be lost. So channels are better to send one-time events. Obviously, you can set reply count for shared flow, but then your event will be repeated.

Follow Me on LinkedIn