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
Assuming
Observeris part of Android UI which isActivityorFragmentandLiveDatais part ofViewModel,Observerwill be local to thatObserver, if Activity gets restarted due to anyConfigchanges, your data insideActivitywill be destroyed unless you save it somehow, butLiveDatapersists activity recreation, so if you have transformation in Observer side, it have to do it every time , but in case ofLiveData, transformed data will be cached and will be provided every time you call it.