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
Observer
is part of Android UI which isActivity
orFragment
andLiveData
is part ofViewModel
,Observer
will be local to thatObserver
, if Activity gets restarted due to anyConfig
changes, your data insideActivity
will be destroyed unless you save it somehow, butLiveData
persists 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.