I am having some trouble with assisted Injection in Hilt and Jetpack Compose. I have set stuff up like here https://medium.com/scalereal/providing-assistedinject-supported-viewmodel-for-composable-using-hilt-ae973632e29a
Just for the sake of it... Code look like this:
ViewModel Implementation. The ViewModel is in the "feature" module:
class NoteDetailViewModel @AssistedInject constructor(
@Assisted private val noteId: String,
private val notyTaskManager: NotyTaskManager,
private val noteRepository: NotyNoteRepository
) : ViewModel() {
// Other ViewModel's implementation...
@AssistedFactory
interface Factory {
fun create(noteId: String): NoteDetailViewModel
}
@Suppress("UNCHECKED_CAST")
companion object {
fun provideFactory(
assistedFactory: Factory,
noteId: String
): ViewModelProvider.Factory = object : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return assistedFactory.create(noteId) as T
}
}
}
}
@Module
@InstallIn(ActivityRetainedComponent::class)
interface AssistedInjectModule
Then, in the MainActivity
, which is the only Activity in the app anyway (app module):
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@EntryPoint
@InstallIn(ActivityComponent::class)
interface ViewModelFactoryProvider {
fun noteDetailViewModelFactory(): NoteDetailViewModel.Factory
}
...
And lastly, the @Composable
looks like this (located in the feature module):
@Composable
fun noteDetailViewModel(noteId: String): NoteDetailViewModel {
val factory = EntryPointAccessors.fromActivity(
LocalContext.current as Activity,
MainActivity.ViewModelFactoryProvider::class.java
).noteDetailViewModelFactory()
return viewModel(factory = NoteDetailViewModel.provideFactory(factory, noteId))
}
Can anybody help? Thanks!
There's a couple of problems:
Firstly, the MainActivity.ViewModelFactoryProvider::class.java
is not accessible in the feature module. Obviously you can't create a circular reference. That's why I tried replacing it with NoteDetailViewModel.Factory
; it should be the same, right? Unfortunately I get an error saying "cannot cast from Singleton_C to NoteDetailViewModel".
Putting the Composable function in the MainActivity file might also be a solution, but that doesn't work either, obviously...
I solved it another way in the end, using an Annotation class. It works, but I'd like to use the assisted injection.