Hello, can stateflow completely replace Livedata as there is LifecycleScope?
v
Viktor De Pasquale
08/16/2023, 10:27 AM
The problem is LiveData was never meant to be reactive component but rather storage for data of sorts.
Not only StateFlow replaces it but adds whole ton of features and reactivity to it! To achieve the similar behavior you need to collect it in a lifecycle scope (that is fragment.lifecycleScope or activity.lifecycleScope) or viewModelScope.
For compose you call .collectAsState() methods and supply appropriate arguments, it’s automatically collected correctly for you
💯 1
g
gildor
08/21/2023, 1:35 AM
Great reply from Viktor, I would just add that if you want exactly the same behavior as LiveData (to pause observing event onStop and resume onStart), use flowWithLifecycle
Also not necessary StateFlow, which always has value (as LiveData), but Flow too, it's actually more flexible API than LiveData