š StateFlow, End of LiveData?
In this article, weāll learn how to use Kotlin Coroutine StateFlow
in Android instead of LiveData.
In the recent release of Kotlin coroutines library (1.3.6), you can see there a new class ā StateFlow
. So whatās this and how it works? Letās seeā¦
What is StateFlow
?š¤·āāļø
- Itās basically a new primitive for state handling.
- Itās designed to eventually replace
ConflatedBroadcastChannel
for state publication scenarios. - It is a flow that emits updates to its collectors.
- Value can be observed by collecting values from the flowš.
Still not getting? Hereās a quick demo to understand ā
I think now you get it whatās exactly ā StateFlow
š. So whatās happening here is whenever weāre updating the value of stateFlow then it emits value to its collectors.
To manage state in Android we generally used Android Arch. componentās LiveData which is lifecycle-aware. We can replace it with StateFlow. Letās see how to use it with Android. Letās write some code!
ā”ļø Getting Started
Open Android Studio and create a new project. Alternatively, you can simply clone this repository. This is a very simple counter app for demonstrating the use of Kotlin Coroutineās StateFlow API.
Weāll be using MainViewModel
to manage our data of MainActivity
.
Now you can compare its implementation using LiveData.
MutableStateFlow
has a setter property for value.- Weāve declared an instance of
StateFlow
i.e. countState which weāre exposing for activity (Itās a read-only field). StateFlow
has a property called value by which you can be safely read at any time.
Now letās implement our MainActivity
ā
Here, weāve initialized ViewModel for activity. Now letās implement the initView()
method which will initialize our Counter App UI.
Everything looks cool now! š. Letās observe for count value now to keep track of counting and show it on UI accordingly.
Hereās we have collector which will be executed whenever the value of a countState is updated. We also made it lifecycle-aware as weāve used it under lifecycleScope
. It looks simple, right? Thatās it! š
Now letās run this app and see if itās working.
Aināt it Sweettttt š.
We can implement the same using LiveData too. Whatās different then? š¤·āāļø
We can use powerful flow operators with StateFlow
like combine, zip, etc which can give us more great experience than LiveData. Yes, thatās it.
Final Words:
StateFlow
is really easy to handle and implement.- Currently, it doesnāt support LiveDataās
onActive()
oronInactive()
like callbacks but this will be possible onceSharedFlow
is officially released š. - Its behaviour is the same as
LiveData
along with more operators and great performance š. Then we should consider using it instead of LiveData.