当不再需要注入的字段时,Dagger 2如何处理?

时间:2018-08-30 07:59:18

标签: android kotlin dagger-2 leakcanary dagger

我有一个关于将多个片段注入活动字段的问题。目前,我已经进行了这样的设置(所有片段都扩展了DaggerFragment并且活动是DaggerAppCompatActivity):

@Inject
lateinit var fragmentOne: FragmentOne
@Inject
lateinit var fragmentTwo: FragmentTwo
@Inject
lateinit var fragmentThree: FragmentThree

override fun onCreate(...) {
    ...
    startFirstFragment()
}

fun startFirstFragment() {
    supportFragmentManager.beginTransaction()
            .replace(containerId, fragmentOne).commit()
}

fun startSecondFragment() {
    supportFragmentManager.beginTransaction()
            .replace(containerId, fragmentTwo).commit()
}

一切正常,直到我添加LeakCanary,它说,当我用第二个替换第一个片段时,被替换的实例通过lateinit var fragmentOne泄漏,因为它保留了对第一个片段的引用。我的问题是:什么时候匕首会清空字段,它是正确地做到了?应该归咎于谁:匕首会导致泄漏,LeakCanary会导致误报泄漏检测?

ApplicationComponent:

@ApplicationScoped
@Component(
        modules = [
            AndroidSupportInjectionModule::class,
            ActivityBindingModule::class,
            ApplicationModule::class,
            RepositoriesModule::class,
            NetworkModule::class]
)
interface ApplicationComponent : AndroidInjector<MyApp> {

    override fun inject(instance: MyApp?)

    @Component.Builder
    interface Builder {

        @BindsInstance
        fun application(application: Application): Builder
        fun build(): ApplicationComponent
    }
}

ActivityBindingModule:

@Module
abstract class ActivityBindingModule {

    ...

    @ActivityScoped
    @ContributesAndroidInjector(modules = [ActivityInQuestionModule::class])
    internal abstract fun aiqActivity(): ActivityInQuestion

    @ActivityScoped
    @Binds
    internal abstract fun fragmentSwitcher(activityInQuestion: ActivityInquestion): FragmentSwitcher

}

ActivityInQuestionModule:

@Module
abstract class ActivityInQuestionModule {

    @FragmentScoped
    @ContributesAndroidInjector
    internal abstract fun fragmentOne(): FragmentOne

    @FragmentScoped
    @ContributesAndroidInjector
    internal abstract fun fragmentTwo(): FragmentTwo

    @FragmentScoped
    @ContributesAndroidInjector
    internal abstract fun fragmentThree(): FragmentThree

}

1 个答案:

答案 0 :(得分:0)

我很确定匕首不是泄漏的原因(如果存在的话)。匕首所做的只是用适当的实例实例化活动的成员。因此,您可以尝试使用修改后的代码运行lateinit var fragmentOne = FragmentOne() ...来运行LeakCarnary,并验证是否存在内存泄漏。也许问题出在您的片段代码中。