Transforming LiveData
Sometimes, the LiveData you pass from the ViewModel to the UI layer needs to be processed first before displaying. For example, you can only select a part of the data or do some processing on it first. In the previous exercise, you filtered the data to only select popular movies from the current year.
To modify LiveData, you can use the Transformations
class. It has two functions, Transformations.map
and Transformations.switchMap
, that you can use.
Transformations.map
modifies the value of LiveData into another value. This can be used for tasks like filtering, sorting, or formatting the data. For example, you can transform movieLiveData
into string LiveData from the movie's title:
private val movieLiveData: LiveData<Movie> val movieTitleLiveData : LiveData<String> = Â Â Â Transformations.map(movieLiveData) { it.title }
When movieLiveData
changes value, movieTitleLiveData
will also change based on the movie's title...