LiveData is dead! Long live StateFlow!
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.
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.