【问题标题】:What does it basically mean with scope annotations in two components (one depends on the other)两个组件中的范围注释基本上意味着什么(一个取决于另一个)
【发布时间】:2019-10-24 18:24:27
【问题描述】:

在我的 Android 项目中,我有两个项目模块,一个 main 模块和一个 core 模块。

在主模块中,我有一个匕首组件,MainComponent

 // it has dependency on CoreComponent
@Component(modules = [MyModule::class], dependencies = [CoreComponent::class])
@FeatureScope
interface MainComponent {
    fun inject(mainActivity: MainActivity)
}

如上所示,MainComponent 依赖于CoreComponent。它还有一个自定义范围注解@FeatureScope

core 模块中,我有另一个名为CoreComponent 的匕首组件:

@Component(modules = [CoreModule::class])
@Singleton
interface CoreComponent {
    fun getExpensiveObject(): ExpensiveObject
}

@Module
class CoreModule {
    @Provides
    @Singleton
    fun provideExpObj(): ExpensiveObject = ExpensiveObject()
}

CoreComponent 由 Dagger 定义的 @Singleton 范围注解。

我在Application 类的onCreate() 中构建主组件:

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
          //build main component along with core component
         mainComponent = DaggerMainComponent
                .builder()
                .myModule(MyModule())
                .coreComponent(DaggerCoreComponent.builder().build())
                .build()
     }
}

CoreComponent 及其提供者由@Singleton 注释,而MainComponent 及其提供者由自定义注释@FeatureScope 注释。

问题一: 从生命周期的角度来看,代码是否意味着MainComponent 中对象的生命周期比CoreComponent 中的对象生命周期短,原因是范围注释(CoreComponent 中的@Singleton 和@ 987654343@ 在 MainComponent)?

问题二:由于组件是在ApplicationonCreate()中构建的,这是应用程序在运行时的入口点,即使两个项目模块中的组件都被注释了,我对吗?不同的范围注解,它们的对象基本上和整个应用程序在运行时的生命周期相同?

(我问这些问题是因为我的理解是 Dagger 定义的 @Singleton 范围的生命周期最长,但我对我的项目感到困惑)

【问题讨论】:

    标签: android dagger-2


    【解决方案1】:

    是的,CoreComponent 被注释为@Singleton 并且组件实例是在Application 中创建的,这意味着在应用程序的生命周期中将创建一个ExpensiveObject

    关于自定义注解(@FeatureScope

    组件实现确保每个组件实例的每个作用域绑定只有一个规定。 ref

    但由于 MainComponent 在每个应用程序中只创建一次,因此此自定义注释实际上与 Singleton 注释相同。

    如果你想要一个功能范围的对象,那么你应该从MainComponent 中删除它,并且只在子组件上使用这个注释。阅读匕首教程,尤其是step 13

    注释WithdrawalLimiterUserCommandsRouter @PerSession 向 Dagger 表明单个 WithdrawalLimiter 应该 为UserCommandsRouter 的每个实例创建。

    @PerSession
    final class WithdrawalLimiter { ... }
    
    @PerSession
    @Subcomponent(...)
    interface UserCommandsRouter { ... }
    

    【讨论】:

      猜你喜欢
      • 2010-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-31
      • 2020-07-09
      • 2020-09-16
      • 2021-09-24
      相关资源
      最近更新 更多