问题描述
我正在使用Dagger
,我想@inject
一个Repository
到我的ViewModel
,所以我在我的Map
存储库类中创建了一个抽象模块:
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:
我的抽象模块:
@Module
abstract class RepositoryModule{
@Binds
@IntoMap
@ClassKey(RepositoryStatus::class)
abstract fun provideRepositoryStatus(repositoryStatus: RepositoryStatus): RepositoryStatus
}
我的ViewModel
模块,其中包含RespositoryModule
:
@Module(includes = [
RepositoryModule::class
])
abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(MainViewModel::class)
abstract fun bindsMainViewModel(viewModel: MainViewModel): ViewModel
}
我不知道这是如何工作的,怎么假设Dagger知道我有一张地图,然后将其与我的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.
推荐答案
@Binds
与@Provides
类似,仅用于提供接口,抽象类或扩展的案例类.因此,无需进行任何配置,并且@Provides
调用是不必要的.
@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.
虽然@IntoMap
用作将put
密钥输入地图的命令,在这种情况下,密钥由@ClassKey
或@ViewModelKey
提供,而值由@Binds
提供.
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
.
也请检查文档,因为我的解释是针对您的具体情况的.但这是最基本的.在Daggers Javadoc中:
Please also check the documentation, because my explanation is for your case specific. But that's the basic. From the Daggers Javadoc:
@Binds
@Binds
@IntoMap
@IntoMap
这篇关于@IntoMap @Binds如何与Dagger完全兼容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!