android / codelab-android-hilt

Apache License 2.0
356 stars 190 forks source link

Custom Qualifier not working in ViewModel #25

Open choongyouqi opened 3 years ago

choongyouqi commented 3 years ago

When I introduce a View Model as below,

@HiltViewModel
class MainViewModel @Inject constructor(
    @InMemoryLogger private val logger: LoggerDataSource,
    private val savedStateHandle: SavedStateHandle
) : ViewModel()

it will hit the following build error:

error: [Dagger/MissingBinding] @com.example.android.hilt.di.InMemoryLogger com.example.android.hilt.data.LoggerDataSource cannot be provided without an @Provides-annotated method.
  public abstract static class SingletonC implements LogApplication_GeneratedInjector,

used to be working fine back in the @ViewModelInject days

manuelvicnt commented 3 years ago

In which Hilt component is the @InMemoryLogger binding installed? It should be part of the SingletonComponent

choongyouqi commented 3 years ago

it did work after converting the component to SingletonComponent. but is SingletonComponent really the requirement to use DI with ViewModel?

I have created a branch demonstrating @ActivityScoped @InMemoryLogger working in hilt-2.28.3-alpha https://github.com/choongyouqi/android-hilt/tree/feature/viewmodel_old

This is the sample using @HiltViewModel in hilt-2.38.1 that I have to resort using SingletonComponent https://github.com/choongyouqi/android-hilt/tree/feature/viewmodel_new

manuelvicnt commented 3 years ago

It doesn't need to be scoped or installed in the SingletonComponent. You could have the qualifier applied to an unscoped type, for example.

If you take a look at the components hierarchy, ViewModelComponent that is what @ViewModelInject uses is a subcomponent of ActivityRetainedComponent.