Skip to content

Difference between LiveData, StateFlow, Flow, SharedFlow

Devrath edited this page Nov 13, 2021 · 3 revisions

LiveData

  • 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.

StateFlow

  • Flow is comparable to live data but it can do a little bit more.
  • State flow is the most comparable one to live 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 of live data because, live data is kind of obsolete and the flow provides more things like flow operators using which we can transform the data. Also testing is easier in flow than the live data.
  • We know flows have 2 types of flows, hot flow and cold flow. State flow is a hot 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 in state flow, it will trigger again.

Flow

  • Normal flow is just simple flow, meaning unlike live data and state flow a normal 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

  • 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.
Clone this wiki locally