-
Couldn't load subscription status.
- Fork 24
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 holdermeaning 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.
-
Flowis comparable tolive databut it can do a little bit more. -
State flowis the most comparable one tolive databecause it can store a state. - It is also a flow and that is the benefit -> kind of ->
Stateflow = flow + LiveData. -
Flowis 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 databecause,live datais kind of obsolete and theflowprovides more things likeflow operatorsusing which we can transform the data. Alsotestingis easier inflowthan thelive data. - We know flows have 2 types of flows,
hot flowandcold flow.State flowis ahot flowmeaning even if there are no observers the flow will be emitted. -
State flowneeds an initial value. -
StateFlowkeeps 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 flowis just simple flow, meaning unlikelive dataandstate flowanormal flowcan'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.
-
SharedFlowdoes 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 flowdoes. 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.
