Switch to dagger

Why and how you should switch to Dagger 2.12+? By Gabriel Samojło

Posted on Leave a commentPosted in bitcraft, Know-how

Dependency Injection is good. Yeah, we all know it. And yes, we were using it for a while. But were we using it correctly? Was it easy? Uhm. It depends. But one thing is sure: now it’s better. Just to make it clear: it’s not a Dagger tutorial. If you are not familiar with it, I recommend for you to read a bit, as it’s great and you definitely should learn Dagger and start using it in your projects. Okay. So what’s the deal with this all-new Dagger? Well… it came with Android support. As you know, Dagger is Java library, not the Android one. So all the stuff we were doing with Dagger was pure Java Dependency Injection. But was it wrong? Why it is a problem? It’s simple — many of Android framework classes are instantiated by Android itself so we had to perform injection inside of lifecycle methods. By that, we were copy-pasting pretty long builders into our onCreate() methods. I guess you know that: ((MyApplication) getApplication()) .getAppComponent() .build() .inject(this); Pretty scary, right? It’s really not how dependency injection should look like. It obviously breaks one of the most important rules of it: “A class shouldn’t know anything about […]