LiveData is dead! Long live StateFlow!

Joost Klitsie
5 min readAug 17, 2024

LiveData has fulfilled it purpose, but still some people seem to be unable to let go and even in 2024 I see articles being written that use LiveData. So lets go over some of the problems with LiveData, and hopefully I can convince you to move on, once and for all.

Courtesy of Imgflip

Problem #1: Null safety

LiveData is not null safe! As you can see, you always have to check for null when you get the value. It is very bad for a state to be uninitialized.

val myLiveData = MutableLiveData<Int>()
println(myLiveData?.times(5))
// Prints: null

val myLiveData2 = MutableLiveData(2)
println(myLiveData2?.times(5))
// Prints: 10


// StateFlow:

val myStateFlow = MutableStateFlow(2)
println(myStateFlow.value.times(5))
// Prints: 10

Problem #2: Lifecycle reliance

A LiveData may not do what you want it to do when there is no UI observing on it. LiveData offers a lot of functions, like mapping, or you can combine LiveData’s using a mediator LiveData. So LiveData is quite a reactive stream of data, but sadly you can not really use it far away from any lifecycle component and you cannot use it properly to store observable data inside a repository (trust me, I tried…). A MutableStateFlow will always have your back, you can run work using whatever CoroutineScope you want.

--

--

Joost Klitsie
Joost Klitsie

Written by Joost Klitsie

I am developing Android Applications for over 10 years, with a passion for Kotlin, and won Best of Swiss Apps in 2023 with my team.