Advertisement
strok_777

DetailViewModel

Feb 4th, 2021
902
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.46 KB | None | 0 0
  1. class DetailViewModel(
  2.     private val getRecipeById: GetRecipeById,
  3.     private val getRecipeSummary: GetRecipeSummary,
  4.     private val toggleRecipeFavorite: ToggleRecipeFavorite,
  5.     override val uiDispatcher: CoroutineDispatcher,
  6.     private val recipeId: Int) : ScopedViewModel(uiDispatcher) {
  7.  
  8.     data class UiModel(val recipeId: Int, val title: String, val summary: String, var favorite: Boolean, val image: String)
  9.  
  10.     private lateinit var recipe : Recipe
  11.  
  12.     private val _model = MutableLiveData<UiModel>()
  13.     val model: LiveData<UiModel>
  14.         get() {
  15.             if (_model.value == null) getSummary(recipeId)
  16.             return _model
  17.         }
  18.  
  19.     private fun getSummary(id: Int) {
  20.         launch {
  21.             recipe = getRecipeById.invoke(id)
  22.             recipe.let {
  23.                 _model.value = getRecipeSummary.invoke(id)?.let { it1 ->
  24.                     UiModel(
  25.                             recipe.id,
  26.                             recipe.title,
  27.                             it1.summary,
  28.                             recipe.favorite,
  29.                             recipe.image
  30.                     )
  31.                 }
  32.             }
  33.         }
  34.     }
  35.  
  36.     fun onFavoriteClicked() {
  37.         launch {
  38.             _model.value?.let {
  39.                 _model.value = UiModel(it.recipeId, it.title, it.summary, !it.favorite, it.image)
  40.                 toggleRecipeFavorite.invoke(recipe.id, !it.favorite)
  41.             }
  42.         }
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement