Skip to content

Instantly share code, notes, and snippets.

@tfcporciuncula
Created August 31, 2018 08:29
Show Gist options
  • Save tfcporciuncula/b389a1b4b583a643c4b7c1ca9ab9ba6c to your computer and use it in GitHub Desktop.
Save tfcporciuncula/b389a1b4b583a643c4b7c1ca9ab9ba6c to your computer and use it in GitHub Desktop.
Dagger injection in activities according to the docs
((SomeApplicationBaseType) getContext().getApplicationContext())
.getApplicationComponent()
.newActivityComponentBuilder()
.activity(this)
.build()
.inject(this);
@bsautner
Copy link

bsautner commented Apr 23, 2019

I found that ((SomeApplicationBaseType) getContext().getApplicationContext()) can lead to a ClassCastException when some phone manufacturers override getApplicationContext() and you don't get your Application class back. I had to find this in production with my app on millions of phones to track it down on a few 1000 app crashes but it's true. I was lead to this snippet from a nice article on Dagger 2.

I'm pretty good at dagger but getting used to kotlin, I did realize there isn't any real reason to have your Dagger components in the Android App class and a static object will suffice - like this:


object MyComponentProvider {


    var myComponent: myComponent? = null

    fun getInstance(context: Context) : MyComponent? {

        if (myComponent == null) {
           myComponent = DaggerMyComponent.builder().myModule(MyModule(context)).build();
        }

        return myComponent;
    }


    //for scoped dagger graphs use this to dispose of it and have it GC
    fun dispose() {
        myComponent = null
    }




}

I'm sure some kotlin master can improve upon that, but i'm quite sure of the app crash casting problem

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment