LiveData transformations map functionality

6.6k Views Asked by At

Recently i've been learning transformations methods on LiveData

I know that we can use map or switchMap method to transform livedata. Let's say we have Player data class similar below

data class Player(val name: String, val score: Int = 0)

And we use map method to transform player livedata to playerName livedata

val player: LiveData<Player> = ...

val playerName: LiveData<String> = 
    Transformations.map(player) { it.name }

My question is, what is the difference doing it in observer function as they both run in main thread? I mean, if we want to get playerName then we can get it in observer function too. Why we declare second LiveData instance to get that

I took example code from this guide : https://proandroiddev.com/livedata-transformations-4f120ac046fc

1

There are 1 best solutions below

0
On BEST ANSWER

Assuming Observer is part of Android UI which is Activity or Fragment and LiveData is part of ViewModel,

  • Doing the transformations in Observer will be local to that Observer, if Activity gets restarted due to any Config changes, your data inside Activity will be destroyed unless you save it somehow, but LiveData persists activity recreation, so if you have transformation in Observer side, it have to do it every time , but in case of LiveData, transformed data will be cached and will be provided every time you call it.
  • Second thing is UI should be as dumb as possible, make all your data transformations before data reaches the UI. This way you can test your transformations using Unit Test without actually needing to rely on UI.