Learning Android Development

Explore LiveData & StateFlow Value Emitting Behavior

Understanding the Different and Similarity of LiveData and StateFlow value emitting

Photo by Paolo Chiabrando on Unsplash

LiveData vs. StateFlow is a hot topic in Android development today. Which to use what?

I read an article that advocates for LiveData, and also an article that advocates for StateFlow. So much to digest. To start off, I begin my little experiment instead.

Understanding the basic

LiveData has 2 emitting functions: Post and Set

One of the articles states that the downside of LiveData is that it has two value emitting functions i.e. setValue and postValue

  1. setValue — It can only be used on the main thread. Else it will crash.
  2. postValue — It can be used on any thread. But if the main thread is busy, the value will drop (got lost), only the latest posted value will be used.

StateFlow has only 1 emitting function

There is no set nor post. It’s just the stateFlow.value for one to set. So nothing to worry about if it is background or foreground (main thread).

--

--