Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added SavedStateHandle to avoid unnecessary repository call #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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<Int>()

private val _character = _id.switchMap { id ->
repository.getCharacter(id)
}
val character: LiveData<Resource<Character>> = _character


fun start(id: Int) {
_id.value = id
}

val character: LiveData<Resource<Character>> =
repository.getCharacter(
savedStateHandle.get<Int>("id")
?: throw Exception("You need to pass character id")
)
}