• New Android Injector with Dagger 2 — Part 2
  • Author of Mert şek
  • Translation from: The Gold Project
  • This article is permalink: github.com/xitu/gold-m…
  • Translator: woitaylor
  • Proofreader: XPGSnail LeviDing
  • Dagger New Android Injector: Dagger 2 (1)
  • Dagger New Android Injector: Dagger 2
  • Dagger New Android Injector: Dagger 2

In my last blog I tried to explain the dagger Android injection. I received a few comments from people who said it was too complicated and there was no need to upgrade to use the new features. I thought this would happen, but I still feel the need to explain what dagger is doing behind the scenes. I highly recommend reading the first blog before reading this one. In this article I use * * * * _ @ ContributesAndroidInjector_ annotations to simplify the code in the last blog.

Let’s take a look at the picture below to recall the dagger structure from the first blog.

Let’s examine the graph step by step. I’ll only cover the MainActivity section. The rest of the logic is the same.

  • To create aAppComponentAppModule.
  • createMainActivity.MainActivityComponent.MainActivityModule.
  • mappingMainActivityActivityBuilder(so thatdaggerYou can tellMainActivityWill be injected).

Let’s get started. Call AndroidInject.inject (this) in the MainActivity and add the method that generates the instance to the MainActivityModule.

We just want to inject MainActivity, but we do a lot of things. Can you simplify it further? How to simplify?

  • @SubcomponentannotationsMainActivityComponentDetailActivityComponentIt just acts like a bridge in the picture. We can easily write these two classes.
  • Every time we addUIComponent as a newsubcomponentMust be theactivityMap toActivityBuilder module. This work is often repetitive.

Don’t do repetitive tasks

The writers of Dagger are obviously aware of this problem as well and have come up with a new solution. And there was this new annotations – @ ContributesAndroidInjector, use the comments we can easily add activities/fragments could to the structure of the dagger. The following figure shows the simplified dagger structure. The code is shown later.

I think you can get a better sense of it by looking at the structure above. The revised code is shown here.

You can also pull code from the Android Injection branch.


Diggings translation project is a community for translating quality Internet technical articles from diggings English sharing articles. The content covers the fields of Android, iOS, front end, back end, blockchain, products, design, artificial intelligence and so on. For more high-quality translations, please keep paying attention to The Translation Project, official weibo and zhihu column.