From ba8a7e4cac18770ef3eb3b733828305288fa3414 Mon Sep 17 00:00:00 2001 From: gokberkyagci Date: Sat, 19 Dec 2020 17:58:07 +0300 Subject: [PATCH] Added SavedStateHandle to avoid unnecessary repository call --- .../CharacterDetailFragment.kt | 1 - .../CharacterDetailViewModel.kt | 27 +++++++------------ 2 files changed, 10 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/com/example/rickandmorty/ui/characterdetail/CharacterDetailFragment.kt b/app/src/main/java/com/example/rickandmorty/ui/characterdetail/CharacterDetailFragment.kt index 325eee1..e343ec7 100644 --- a/app/src/main/java/com/example/rickandmorty/ui/characterdetail/CharacterDetailFragment.kt +++ b/app/src/main/java/com/example/rickandmorty/ui/characterdetail/CharacterDetailFragment.kt @@ -32,7 +32,6 @@ class CharacterDetailFragment : Fragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - arguments?.getInt("id")?.let { viewModel.start(it) } setupObservers() } diff --git a/app/src/main/java/com/example/rickandmorty/ui/characterdetail/CharacterDetailViewModel.kt b/app/src/main/java/com/example/rickandmorty/ui/characterdetail/CharacterDetailViewModel.kt index 9e99276..4e1ce90 100644 --- a/app/src/main/java/com/example/rickandmorty/ui/characterdetail/CharacterDetailViewModel.kt +++ b/app/src/main/java/com/example/rickandmorty/ui/characterdetail/CharacterDetailViewModel.kt @@ -1,28 +1,21 @@ package com.example.rickandmorty.ui.characterdetail +import androidx.hilt.Assisted import androidx.hilt.lifecycle.ViewModelInject -import androidx.lifecycle.LiveData -import androidx.lifecycle.MutableLiveData -import androidx.lifecycle.ViewModel -import androidx.lifecycle.switchMap +import androidx.lifecycle.* import com.example.rickandmorty.data.entities.Character import com.example.rickandmorty.data.repository.CharacterRepository import com.example.rickandmorty.utils.Resource +import java.lang.Exception class CharacterDetailViewModel @ViewModelInject constructor( - private val repository: CharacterRepository + @Assisted private val savedStateHandle: SavedStateHandle, + repository: CharacterRepository ) : ViewModel() { - private val _id = MutableLiveData() - - private val _character = _id.switchMap { id -> - repository.getCharacter(id) - } - val character: LiveData> = _character - - - fun start(id: Int) { - _id.value = id - } - + val character: LiveData> = + repository.getCharacter( + savedStateHandle.get("id") + ?: throw Exception("You need to pass character id") + ) }