-
Notifications
You must be signed in to change notification settings - Fork 22
Difference between LiveData, StateFlow, Flow, SharedFlow
Devrath edited this page Nov 13, 2021
·
3 revisions
- Live data is the most well-known observer pattern among all because it is the oldest.
- This belongs to android Jetpack.
- This is among the only ones that work on Java.
- LiveData is a
state holder
meaning it holds the UI state in it, say suppose we have some text elements that have set some state in the screen and the screen rotates, the live data will hold the value in its container and it will set it. - Live data is life cycle aware, it will only fire in the scenario where the states must receive the values, like if the activity is in the foreground basically.
- So when we rotate the screen, it will fire again and lifecycle aware also that the last value present in the container is populated.
-
Flow
is comparable tolive data
but it can do a little bit more. -
State flow
is the most comparable one tolive data
because it can store a state. - It is also a flow and that is the benefit -> kind of ->
Stateflow = flow + LiveData
. -
Flow
is based on the coroutine framework so we need to use a scope to listen to the state flow. - Rotate the screen, value will retain.
- Then
why to use the flow instead of live data
, W should go for using the flow instead oflive data
because,live data
is kind of obsolete and theflow
provides more things likeflow operators
using which we can transform the data. Alsotesting
is easier inflow
than thelive data
. - We know flows have 2 types of flows,
hot flow
andcold flow
.State flow
is ahot flow
meaning even if there are no observers the flow will be emitted. -
State flow
needs an initial value. -
StateFlow
keeps a value once set, when triggered again, if the value is the same, it won't emit again. Say if we rotate the screen and if a value is stored instate flow
, it will trigger again.
-
Normal flow
is just simple flow, meaning unlikelive data
andstate flow
anormal flow
can't store data. It will emit till completion and stop emoting. - On-screen rotation will start emitting the data again all over again when triggered.
-
SharedFlow
does not need an initial value. - It is also a
hot flow
. - It just sends a one-time event, it is not triggered automatically when the screen rotates like the
state flow
does. And explicitly triggered it will trigger again. - Triggering and receiving a shared flow, we need a scope
- Unlike the flow shared flow does not need a flow builder also.