ΓDΛ
ΓDΛ

Reputation: 11060

What are the differences between StateFlow and LiveData?

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.

  1. What are the differences in terms of performance?
  2. In which scenarios does it provide advantages?
  3. Using StateFlow with Kotlin Flow is advantageous. But what is the risk of not switching to StateFlow in a project using LiveData?
  4. Is Google deprecating LiveData? :)

Upvotes: 18

Views: 6123

Answers (1)

Sam Chen
Sam Chen

Reputation: 8847

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?

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

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

  3. 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" :).

Upvotes: 18

Related Questions