Search code examples
kotlinandroid-jetpack-composedagger-hiltassisted-inject

Hiltviewmodel in jetpack compose with AssistedInject multiple errors


I have a viewModel in my application that gets some runtime argument (Let's call it someId). As I searched I came across the AssistedInject functionality and updated my Hilt to version 1.2.0.

Now here is how I try to achieve this functionality:

  1. On My first try:

In my MyViewModel.kt I have:

@HiltViewModel(assistedFactory = MyViewModelFactory::class)
class MyViewModel @AssistedInject constructor(
    @Assisted val someId: Int?
) : ViewModel() {
...
}

@AssistedFactory
interface MyViewModelFactory {
    fun create(someId: Int?): MyViewModel
}

And in my composable I have :

 val viewModel : MyViewModel = hiltViewModel<MyViewModel, MyViewModelFactory>{factory ->
        factory.create(myIdVariable)
    }

and the result is, when I build the app, I get error :

[Hilt] ViewModel constructor should be annotated with @Inject instead of @AssistedInject.
  1. In order to fix the error, I do these changes:

In my MyViewModel.kt I have:

@HiltViewModel(assistedFactory = MyViewModelFactory::class)
class MyViewModel @Inject constructor(
    @Assisted val someId: Int?
) : ViewModel() {
...
}

and when I build the application, I get this error:

on the generated MyViewModelFactory:

An assisted factory's abstract method must return a type with an @AssistedInject-annotated constructor.
  1. On My third try, I do these changes:

In my MyViewModel.kt:

@HiltViewModel
class MyViewModel @Inject constructor(
    @Assisted val someId: Int?,
) : ViewModel() {
...
}

and I get the same error.

  1. So as it makes sense, I do these changes on my 4th try:
@HiltViewModel
class MyViewModel @AssistedInject constructor(
    @Assisted val someId: Int?,
) : ViewModel() {
...
}

and again I get the same error as #1:

[Hilt] ViewModel constructor should be annotated with @Inject instead of @AssistedInject.

So, I've ran out of ideas how to fix the problem and what could cause the problem.

P.S. I've cleaned the project between each build, so that I make sure no old generated code remains, and all the DI is re-generated.


Solution

  • You need to update hilt to 2.49 or newer version:

    Fixed #2287, #3523: Add support for using @AssistedInject with @HiltViewModel. (8327177). For more details visit https://dagger.dev/hilt/view-model#assisted-injection.