9

I am using navigation component for jetpack compose in my app like this:

@Composable
fun FoodiumNavigation() {
    val navController = rememberNavController()

    NavHost(
        navController = navController,
        startDestination = Screen.Main.route,
    ) {
        composable(Screen.Main.route) {
            MainScreen(navController)
        }

        ...
    }
}

And I am getting viewmodel in my MainScreen composable like this:

@Composable
fun MainScreen(navController: NavController) {
    val mainViewModel: MainViewModel = viewModel()
    ...
}

which is giving me a runtime exception as Cannot create an instance of class com.package.main.MainViewModel.

Here, I am stating that this only happens while using navigation component, i.e. everything was working fine and mainViewModel was successfully instantiated before using navigation component in my app.

The MainViewModel is like this:

@ExperimentalCoroutinesApi
@HiltViewModel
class MainViewModel @Inject constructor(private val postRepository: PostRepository) :
    ViewModel() {

    private val _postsLiveDataState = MutableLiveData<UiState<List<Post>>>()
    val postLiveState: LiveData<UiState<List<Post>>> = _postsLiveDataState

    init {
        getPostsState()
    }

    private fun getPostsState() {
        viewModelScope.launch {
            postRepository.getAllPosts()
                .onStart { _postsLiveDataState.value = UiState(loading = true) }
                .map { resource -> UiState.fromResource(resource) }
                .collect { state -> _postsLiveDataState.value = state }
        }
    }
}
Abhimanyu
  • 11,351
  • 7
  • 51
  • 121
Vivek Singh
  • 1,142
  • 14
  • 32

4 Answers4

15

If your @HiltViewModel is scoped to the navigation graph use hiltNavGraphViewModel() instead of viewModel() to initialize. For more reference android documentaion

Update

hiltNavGraphViewModel() is now deprecated, use hiltViewModel() instead

Thanks to Narek Hayrapetyan for the reminder

Loveth
  • 361
  • 3
  • 7
  • 3
    I noticed that `hiltNavGraphViewModel` will return the same view model after navigating to a different view and then back. Would it also be possible to get a new model instance after each navigation? – Duncan Lukkenaer Apr 22 '21 at 14:30
  • 1
    hiltNavGraphViewModel is deprecated, should be used `hiltViewModel ()` instead. – Narek Hayrapetyan Sep 02 '21 at 14:18
4

hiltNavGraphViewModel is deprecated, should be used hiltViewModel() instead

also add dependency androidx.hilt:hilt-navigation-compose:1.0.0-alpha03

Narek Hayrapetyan
  • 1,731
  • 15
  • 27
2

You should add this

implementation("androidx.hilt:hilt-navigation-compose:1.0.0")

then you can use this code for create instance of your viewmodel

val viewModel: YourViewModelClass= hiltViewModel()
Moha.AZ
  • 776
  • 2
  • 5
  • 11
0

You can use viewModel() as well, but check that owning Activity or Fragment has been annotated with @AndroidEntryPoint.

Ziens
  • 381
  • 2
  • 8