as I mentioned in the title, I'm curious about the general differences between the two. Can you help with this? I couldn't find the specific differences as there are complex examples on the internet.
Using StateFlow By using viewLifecyleOwner. lifecycleScope extension, we make the flow consumption lifecycle-aware, just like LiveData does. On destroy, the coroutine context is cancelled. LiveData only emits when the LifecycleOwner is on active state.
Flow: Simple things are harder and complex things are easier. LiveData did one thing and it did it well: it exposed data while caching the latest value and understanding Android's lifecycles. Later we learned that it could also start coroutines and create complex transformations, but this was a bit more involved.
By using LiveData we can only observe the data and cannot set the data. MutableLiveData is mutable and is a subclass of LiveData. In MutableLiveData we can observe and set the values using postValue() and setValue() methods (the former being thread-safe) so that we can dispatch values to any live or active observers.
I just switched to StateFlow
, so this is a great time for me to answer your question.
What are the differences in terms of performance?
Honestly, I don't know, but since it's pushed by Kotlin and Android, just trust them :).
In which scenarios does it provide advantages?
For LiveData
you are not forced to give an initial value, it may end up writing more code in init{}
; But for StateFlow
you are Forced to give an initial value (including null
), it may save your code a bit.
For LiveData
even if you give an initial value, you still need to do Null Check when you access its value
(see this), it's kind of annoying. But that's not gonna happen on StateFlow
- it will be what it should be.
For LiveData
you cannot easily, or elegantly observe data changes JUST inside ViewModel
, you are gona use observeForever()
which is also mentioned in here. But for StateFlow
it's easy, do it like following:
class FirstViewModel() : ViewModel() {
val uiScope = viewModelScope
val name = MutableStateFlow("Sam") //must have initial value
//val name = MutableStateFlow<String?>(null) //null is acceptable
init {
observeName()
}
private fun observeName() = uiScope.launch { //must run in coroutine scope
name.collect { name -> //for Fragment / Activity, use lifecycleScope.launch{}
//do your stuff
}
}
}
Using StateFlow with Kotlin Flow is advantageous. But what is the risk of not switching to StateFlow in a project using LiveData?
What is the risk of not switching to Kotlin in a project using Java? :)
Is Google deprecating LiveData?
I would say yes, and they would say no, no for "not yet to say it loudly" :).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With