Activity

@PerActivity
@Component(modules = [ActivityModule::class])
interface ActivityComponent

应用
@Singleton
@Component(modules = [
    HttpModule::class,
    ApplicationModule::class
])
interface AppComponent

Activity 特定
@Component(
        modules = [LandingModule::class],
        dependencies = [AppComponent::class, ActivityComponent::class]
)
@ActivityContext
interface LandingComponent {
    fun inject(activity: MainActivity)
}

应用
   override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DaggerLandingComponent.builder().build().inject(this)
   }

我收到的错误是AppComponent具有单例范围cannot depend on scoped components:
在这种情况下,什么是正确的解决方案?

最佳答案

解决此问题的一种常用方法是在父组件中添加plus方法。所以从技术上来说ActivityComponentAppComponent + ActivityComponent,而LandingComponentAppComponent + ActivityComponent + LandingComponent

@Singleton
@Component(modules = [
    HttpModule::class,
    ApplicationModule::class
])
interface AppComponent {
    ActivityComponent plus(module: ActivityModule)
}

@PerActivity
@Subcomponent(modules = [ActivityModule::class])
interface ActivityComponent {
    LandingComponent plus(module: LandingModule)
}

@ActivityContext
@Subcomponent(modules = [LandingModule::class])
interface LandingComponent {
    fun inject(activity: MainActivity)
}

应用
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    AppComponent.builder().build().plus(ActivityModule()).plus(LandingModule())
}

07-24 09:47