kotlinandroid-livedatamutablelivedatamediatorlivedataandroid-livedata-transformations

LiveData transformations map functionality


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


Solution

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