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 is Activity
or Fragment
and LiveData
is part of ViewModel
,
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.