uscode

Untitled

Jan 25th, 2021
435
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.example.mymov.ui.detail.viewmodel
  2.  
  3. import androidx.lifecycle.LiveData
  4. import androidx.lifecycle.MutableLiveData
  5. import androidx.lifecycle.Transformations
  6. import androidx.lifecycle.ViewModel
  7. import com.example.mymov.data.source.local.entity.FilmEntity
  8. import com.example.mymov.data.source.local.entity.TvShowEntity
  9. import com.example.mymov.data.MovieRepository
  10. import com.example.mymov.vo.Resource
  11.  
  12. class DetailViewModel(private val movieRepository: MovieRepository): ViewModel() {
  13.  
  14.     var movieId = MutableLiveData<Int>()
  15.  
  16.     fun setSelected(movieId: Int){
  17.         this.movieId.value = movieId
  18.     }
  19.  
  20.     var film: LiveData<Resource<FilmEntity>> = Transformations.switchMap(movieId) { mFilmId ->
  21.         movieRepository.getFilmWithId(mFilmId)
  22.     }
  23.  
  24.     var tv: LiveData<Resource<TvShowEntity>> = Transformations.switchMap(movieId) { mTvId ->
  25.         movieRepository.getTvWithId(mTvId)
  26.     }
  27.  
  28.     fun setFavorite() {
  29.         val filmResource = film.value
  30.         val tvResource = tv.value
  31.  
  32.         if (filmResource != null) {
  33.             val filmWithData = filmResource.data
  34.  
  35.             if (filmWithData != null) {
  36.                 val newState = !filmWithData.favorite
  37.                 movieRepository.setFavoriteFilm(filmWithData, newState)
  38.             }
  39.         } else if (tvResource != null) {
  40.             val tvWithData = tvResource.data
  41.  
  42.             if (tvWithData != null) {
  43.                 val newState = !tvWithData.favorite
  44.                 movieRepository.setFavoriteTv(tvWithData, newState)
  45.             }
  46.         }
  47.     }
  48.  
  49.  
  50. }
  51.  
RAW Paste Data