@IntoMap @Binds如何与Dagger完全兼容? [英] How @IntoMap @Binds exactly works with Dagger?

查看:548
本文介绍了@IntoMap @Binds如何与Dagger完全兼容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

注释委派绑定的Module的抽象方法.为了 例如,要将Random绑定到SecureRandom,模块可以声明 以下:@绑定抽象随机bindRandom(SecureRandom secureRandom); @Binds方法是Provides的替代品 仅返回注入参数的方法.喜欢@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

@IntoMap

方法的返回类型形成a的值的类型参数 Map>,以及带注释的键和 返回的值作为键/值对贡献给地图.这 从积累的价值中产生的Map> 不变的.

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.

这篇关于@IntoMap @Binds如何与Dagger完全兼容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆