Pros, Cons, Conclusion. TLDR; More Cons than Pros.
class Timer {
private val timeLeftMillis = MutableLiveData(5_000L)
fun getTimeLeftMillis(): LiveData<Long> {
return timeLeftMillis
}
// ...
}
- Avoid boilerplate code to listen changes
- Avoid extra code to post changes on the main thread
- Linked with Android lifecycle
- UnitTest clients is easy with
InstantTaskExecutorRule
By design, to get liveData value, you have to do timeLeftMillis.value!!
-
Sometimes, extra arguments have to be provided via observer, for example to give a reason of the changes. You will not be able to use livedata.
-
On some module pure kotlin, the notion of main thread does not exists.
That makes your project incoherent as sometimes API will have liveData, sometimes not.
Imagine a liveData exposed in an API timeLeftMillis: LiveData<Long>
. Imagine you want to expose another getter to get the elapsed time.
Adding this extra getter will force clients intersted by elapsed time to listen changes of another liveData.
LiveData, by design, will force each layer of your architecture to have extra "fields" that will cache your data in RAM.
LiveData are easy to use and great for prototypes, samples or very small apps.
I never use liveData to be able to scale my projects.