Skip to main content

Why LiveData is the best solution (yet) for UI



Why LiveData is the best solution (yet) for UI
As far as I am concerned, there are many developers who don't like LiveData. However, for the UI part, there is no better API to achieve MVVM (or even MVI,or stateful MVVM). Furthermore, makes the UI control very easy.

There might have been some small misconceptions regarding the usage of it, but, if you use LiveData for the purpose it was created, I think that's far better than any other API (for the moment).

Some general misconceptions

- Should I use LiveData over Flow for network calls?

- Should I use LiveData over RxJava for network calls?

- Should I use LiveData for the Database? (somehow accepted, I disagree)

- Should I replace everything with LiveData?

The right questions to ask:

- Can I use Flow/RxJava instead of LiveData for the UI?

And honestly the answer would be a big YES, and it's a nice pattern to use also. But, my strongest point here is that they both were not created for the purpose that they are being used for in this case.

The LiveData API

First of all, let's introduce a myth: LiveData is complicated. Perhaps, the "back-end" of it might be, but that's one of the purposes when someone provides a dependency, and it's not only to reduce boilerplate, but to make the development simpler, even though building it might be complex. If we take Retrofit as an example, it's just a less boilerplate Okhttp thing (or asI like to call it: abstraction over OkHttp). But if we take Android ViewModels as an
example, there is nothing simple behind it. But we just extend a ViewModel....

And the same case with LiveData. Remember, nothing is too simple when it comes to Android and the Observable pattern in general. If you are interested to check the LiveData, here is the code of it.

So, LiveData is simple.

Let's check what I mean with that:

 
  private val _userFirstName = MutableLiveData<String>()
  val userFirstName: LiveData<String> = _userFirstName


And in order to observe it (from Fragment/Activity):

 
  viewModel.userFirstName.observe(viewLifecycleOwner, Observer{ result ->
    userNameTextView.text = result
  })


That's it. This is basic observable pattern.

You have forgotten to unsubscribe at some point.

Actually no. And this is really a strong second argument: LiveData is lifecycle aware.
You don't need to (un)subscribe in order to prevent possible issues.

Note: For specific cases, you can use removeObserver() also.

Can't say it's thread safe, but it actually is.

You are free not to switch to the main thread and instead just use the postValue() method:


  withContext(Dispatchers.IO){
   _userName.value = repository.getUserName() //WON'T WORK
  }


 
  withContext(Dispatchers.IO){
   _userName.postValue(repository.getUserName())
  }


Less verbose

Even though RxJava and StateFlow are already pretty nice option to replace LiveData with, they have more boilerplate than LiveData in whatever the case.
Let's consider RxJava for example:

 
  private val compositeDisposable = CompositeDisposable()

  ...

  fun observeViewModelChanges(){
   compositeDisposable.add(viewModel.usernameOservable())
  }

  ...

  override fun onDestroy(){ 
    compositeDisposable.dispose()
   super.onDestory()
  }


Same case with StateFlow:


  fun observeViewModelChanges(){
    myViewModel.myStateFlow()
     .map{userName -> handleUserName() }
     .launchIn(lifeCycleScope) 
  }


Or worse, in case we don't are not using lifecyclescope:


  private val job = Job()
  private val coroutineScope = CoroutineScope(Dispatchers.Main + job)

  ...

  fun obserViewModelChanges(){
   myViewModel.obserValuesStateFlow()
     .map{userName -> handleUserName() }
    .launchIn(coroutineScope)
  }

  ...

  override fun onDestory(){
   coroutineScope.cancel()
   super.onDestroy()
  }


While in LiveData there is at least one line less:

 
  viewModel.userFirstName.observe(viewLifecycleOwner, Observer{ result ->
   handleResult(result)
  })


Another small misconception:
If I'm right, why is Google making tutorials on Flow by removing LiveData? I'm pretty sure that's only for the sake of the tutorial and learning something new. However, there might be some places where LiveData is worth being replaced with Flow API, like Room database calls, for instance.

onDestroy

In my opinion, LiveData is not going anywhere for some time. Perhaps, we could see some new LiveData which implements StateFlow on the background, in the future, (making a new lifecycle aware StateFlow API) from the Android team, but that could be definitely after the StateFlow exits the Experimental status. Use LiveData and you will have a simpler everyday development.

Stavro Xhardha

Popular posts from this blog

Modularizing your Android app, breaking the monolith (Part 1)

Inspired by a Martin Fowlers post about Micro Frontends, I decided to break my monolithic app into a modular app. I tried to read a little more about breaking monolithic apps in Android, and as far as I got, I felt confident to share my experience with you. This will be some series of blog posts where we actually try to break a simple app into a modularized Android app.

Note: You should know that I am no expert in this, so if there are false statements or mistakes please feel free to criticize, for the sake of a better development. 

What do you benefit from this approach:
Well, people are moving pretty fast nowadays and delivery is required faster and faster. So, in order to achieve this, modularising Android apps is really necessary.You can share features across different apps. Independent teams and less problems per each.Conditional features update.Quicker debugging and fixing.A feature delay doesn't delay the whole app. As per writing tests, there is not too much difference about…

What I learned from Kotlin Flow API

I used to check the docs and just read a lot about flows but didn't implement anything until yesterday. However, the API tasted really cool (even though some operations are still in Experimental state).Prerequisites: If you don't know RxJava it's fine. But a RxJava recognizer would read this faster.Cold vs Hot streamsWell, I really struggled with this concept because it is a little bit tricky. The main difference between cold and hot happened to be pretty simple: Hot streams produce when you don't care while in cold streams, if you don't collect() (or RxJava-s equivalent subscribe()) the stream won't be activated at all. So, Flows are what we call cold streams. Removing the subscriber will not produce data at all, making the Flows one of the most sophisticated asynchronous stream API ever (in the JVM world). I tried to make a illustration of hot and cold streams: Since I mentioned the word asynchronous this implies that they do support coroutines also. Flows vs…

From Gson to Moshi, what I learned

There is no doubt that people are getting away from GSON and I agree with those reasons too. The only advantage GSON has over other parsing libraries is that it takes a really short amount of time to set up. Furthermore, the most important thing is that Moshi is embracing Kotlin support.

First let's implement the dependency:
implementation("com.squareup.moshi:moshi:1.8.0") It's not a struggle to migrate to Moshi. It's really Gson look-a-like. The only thing to do is annotate the object with @field:Json instead of @SerializedName (which is Gsons way for JS representation):

data class User( //GSON way @SerializedName("name") val name: String, @SerializedName("user_name") val userName: String, @SerializedName("last_name") val lastName: String, @SerializedName("email") val email: String ) data class User( //Moshi way @field:Json(name = "name") val name: String, @field:Json(name = "user_name…