我正在使用 Dagger
并且我想 @inject
一个 Repository
到我的 ViewModel
所以我创建我在其中 Map
存储库类的抽象模块:
我的抽象模块:
@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 是如何知道我有一张 map 并将其与我的 ViewModel
绑定(bind)的?因为我从不使用该方法。而且我有一个包含在图表中的 map ,所以我认为除非我调用它,否则它无法使用。
最佳答案
@Binds
类似于 @Provides
,只是它用于提供接口(interface)、抽象类或在您的案例中扩展的类。所以不需要任何配置,也不需要 @Provides
调用。
虽然 @IntoMap
被用作将您的 key put
到 map 中的命令,其中 key 由 @ClassKey
或 @ViewModelKey
在您的情况下,该值由 @Binds
提供。
还请查看文档,因为我的解释是针对您的具体情况的。但这是基本的。来自 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.
关于java - @IntoMap @Binds 如何与 Dagger 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57287180/