java - @IntoMap @Binds 如何与 Dagger 一起工作?

标签 java android kotlin dagger-2

我正在使用 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/

相关文章:

java - 使用 drawimage 和 repaint 时如何替换旧图像

java - 动态选择 Activity 内的单选按钮 View

java - 动态更改 BLE 广告数据 Android

安卓应用程序停止

android - 如何为Gradle解决DexArchiveBuilderException?

java - 使用 pdfbox 从 pdf 中删除不可见的文本

java - 将数据从一个输入流传输到多个输出流的最佳方式

android - 如何在 Android Studio 中运行某个 Activity ?

reflection - 在没有实例的情况下访问 Kotlin 委托(delegate)类型

java - JVM 是否使用 kotlinc 来实现 Kotlin?