@IntoMap @Binds 如何与 Dagger 配合使用?

How @IntoMap @Binds exactly works with Dagger?

我正在使用 Dagger,我想 @inject 一个 Repository 到我的 ViewModel 所以我创建了一个抽象模块,我 Map存储库 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 绑定?因为我从不使用该方法。我有一个包含在图表中的地图,所以我认为除非我调用它才能使用它。

@Binds 类似于 @Provides,只是它用于提供接口,抽象 类 或者在你的情况下 类 是扩展的。因此不需要任何配置,也不需要 @Provides 调用。

虽然 @IntoMap 用作命令 put 您的密钥进入地图,其中密钥由 @ClassKey@ViewModelKey 在您的情况下提供,并且值由 @Binds.

提供

另请查看文档,因为我的解释是针对您的具体情况的。但这是基本的。来自匕首 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.