gpt4 book ai didi

android - Dagger 柄 : Difference between annotating a class @Singleton and a provides function @Singleton

转载 作者:行者123 更新时间:2023-12-04 23:54:52 29 4
gpt4 key购买 nike

我的问题非常简单明了:两个注释/示例之间有什么区别:

例子一

@Singleton
class MySingletonClass() {}

@Module
@InstallIn(FragmentComponent::class)
abstract class MyFragmentModule {
@Provides
fun provideMySingletonClass() = MySingletonClass()
}

示例二

class MySingletonClass() {}

@Module
@InstallIn(FragmentComponent::class)
abstract class MyFragmentModule {

@Singleton
@Provides
fun provideMySingletonClass() = MySingletonClass()
}

我知道的唯一区别是,第二个示例给我以下错误:

error: [Dagger/IncompatiblyScopedBindings] FragmentC scoped with @dagger.hilt.android.scopes.FragmentScoped may not reference bindings with different scopes:

这是否意味着示例 1 中的 @Singleton 注释被简单地忽略了?

最佳答案

在示例一中,您的@Singleton 注释被忽略,但这只是因为您在@Provides 方法中自己调用构造函数。因为 Dagger 不与您的 MySingletonClass 构造函数交互,所以它无法读取或使用注释。

如果您的 @Singleton class MySingletonClass 有一个 @Inject 构造函数——即使是一个空构造函数——那么 Dagger 将能够直接与它交互只要 您还删除了将覆盖构造函数检测的 @Provides fun。完成后,@Singleton 的行为在两种语法中都是相同的。


关于错误消息“错误:[Dagger/IncompatiblyScopedBindings] XXX scoped with @YYY may not reference bindings with different scopes”:@Andrew 这里真正的问题是在示例二中你是尝试在您安装在 FragmentComponent 中的模块中声明 @Singleton 绑定(bind)。 @Singleton 绑定(bind)只能发生在@Singleton 组件中,which in Hilt is SingletonComponent .我记不太清了,但我认为您的示例一(经过我描述的编辑)可以使用单例行为并且不会出现错误,因为 Dagger 会自动选择层次结构中的适当组件来安装您的 MySingletonClass。

关于android - Dagger 柄 : Difference between annotating a class @Singleton and a provides function @Singleton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68865224/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com