问题
I'm using Dagger and i want to @inject a Repository to my ViewModel so i create an abstract module where I Map the repository class:
My abstract module:
@Module
abstract class RepositoryModule{
@Binds
@IntoMap
@ClassKey(RepositoryStatus::class)
abstract fun provideRepositoryStatus(repositoryStatus: RepositoryStatus): RepositoryStatus
}
My ViewModel module where i include the RespositoryModule:
@Module(includes = [
RepositoryModule::class
])
abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(MainViewModel::class)
abstract fun bindsMainViewModel(viewModel: MainViewModel): ViewModel
}
I don't know how exactly works this, how is supposed that Dagger knows I have a map and i bind it with my ViewModel? because i never user the method. And I have a map include in a graph so it can't be used i think unless i call it.
回答1:
@Binds is similar to @Provides, only it is used to provide interfaces, abstract classes or in your case classes that are extended. So there is no need there for any configuration, and @Provides call would be not necessary.
While the @IntoMap is used as a command to put your keys into a map where the key is provided by @ClassKey or @ViewModelKey in your case and the value is provided by @Binds.
Please also check the documentation, because my explanation is for your case specific. But that's the basic. From the Daggers Javadoc:
@Binds
Annotates abstract methods of a Module that delegate bindings. For example, to bind Random to SecureRandom a module could declare the following: @Binds abstract Random bindRandom(SecureRandom secureRandom); @Binds methods are a drop-in replacement for Provides methods that simply return an injected parameter. Prefer @Binds because the generated implementation is likely to be more efficient.
@IntoMap
The method's return type forms the type argument for the value of a Map>, and the combination of the annotated key and the returned value is contributed to the map as a key/value pair. The Map> produced from the accumulation of values will be immutable.
来源:https://stackoverflow.com/questions/57287180/how-intomap-binds-exactly-works-with-dagger