Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dagger2 - Duplicate instance in DoubleCheck

I'm using Dagger v2.12 with dagger-android-support with the following config:

AppComponent

@Singleton
@Component(
        modules = arrayOf(
                AndroidSupportInjectionModule::class,
                AndroidBindingModule::class,
                AppModule::class
        )
)
interface AppComponent : AndroidInjector<App> {
    @Component.Builder
    abstract class Builder : AndroidInjector.Builder<App>()
}

AndroidBindingModule

@Module
abstract class AndroidBindingModule {
    @PerActivity
    @ContributesAndroidInjector(modules = arrayOf(MainModule::class))
    internal abstract fun contributeMainActivityInjector(): MainActivity
}

MainModule

@Module
class MainModule {

    ...

    @Provides @PerActivity
    fun providePresenter(rxLifecycle: ReactiveLifecycle, view: MainView) =
            MainPresenter(rxLifecycle, view)

}

MainActivity

class MainActivity : BaseActivity() {
    @Inject
    lateinit var presenter: MainPresenter

    ...
}

Analysing the memory dump, I noticed that the MainPresenter class has been created twice, one been referenced in MainActivity and dagger.internal.DoubleCheck(as expected) 1, but, there are a second instance referenced only in dagger.internal.DoubleCheck 2.

sample1

sample2

Why this is happening? Is this a bug, expected behaviour or some issue in my Dagger config?

Edit: Sample repository with the issue https://github.com/ismaeldivita/dagger-test-so

like image 792
Ismael Di Vita Avatar asked Nov 03 '17 16:11

Ismael Di Vita


1 Answers

The problem is, that you are performing AndroidInjection.inject(this) 2 times within your activity class. That happens, because your activity is a descendant of DaggerAppCompatActivity, which in turn also performs AndroidInjection.inject(this).

From the docs of DaggerAppCompatActivity:

An AppCompatActivity that injects its members in onCreate(Bundle) and can be used to inject Fragments attached to it.

After omitting AndroidInjection.inject(this) line from your MainActivity class you'll get the expected output in logcat:

enter image description here

like image 123
azizbekian Avatar answered Oct 14 '22 04:10

azizbekian