Skip to content

Instantly share code, notes, and snippets.

@Mercandj
Last active August 30, 2020 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mercandj/3f1588176169026a3c949620c47bb504 to your computer and use it in GitHub Desktop.
Save Mercandj/3f1588176169026a3c949620c47bb504 to your computer and use it in GitHub Desktop.
LiveData: Pros, Cons, Conclusion.

Android: LiveData

Pros, Cons, Conclusion. TLDR; More Cons than Pros.

class Timer {

   private val timeLeftMillis = MutableLiveData(5_000L)
   
   fun getTimeLeftMillis(): LiveData<Long> {
      return timeLeftMillis
   }
   
   // ...
}

Pros

  • 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

Cons

1/ Nullable

By design, to get liveData value, you have to do timeLeftMillis.value!!

2/ Coherence

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

3/ Robustness

Imagine a liveData exposed in an API timeLeftMillis: LiveData<Long>. Imagine you want to expose another getter to get the elapsed time.

Screenshot 2020-08-27 at 10 34 51

Adding this extra getter will force clients intersted by elapsed time to listen changes of another liveData.

4/ Source of truth

LiveData, by design, will force each layer of your architecture to have extra "fields" that will cache your data in RAM.

Conclusion

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment