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:
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.
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.
In my MyViewModel.kt
:
@HiltViewModel
class MyViewModel @Inject constructor(
@Assisted val someId: Int?,
) : ViewModel() {
...
}
and I get the same error.
@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.
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.