Dagger 2 Tutorial For Android: Advanced

In this tutorial, you’ll learn about the advanced concepts of Dagger. You’ll learn about component lifecycles, @Binds, and component builders and factories. By Massimo Carli.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 5 of 5 of this article. Click here to view the first page.

Using the @Component.Factory Interface

Like the Builder, the Factory method is a creational GoF pattern. That means it defines some way of creating instances of a specific class. While the former provides you some methods in to pass what you need, the latter provides you a single method with multiple parameters.

The former defines a build() that the latter doesn’t need. The same difference happens when you use them with Dagger. To prove this, change the AppComponent.kt to the following:

@Component(modules = [AppModule::class])
interface AppComponent {

  fun inject(frag: NewsListFragment)

  fun inject(frag: NewsDetailFragment)

  // 1
  @Component.Factory
  interface Factory {
    // 2
    fun repository(@BindsInstance repo: NewsRepository): AppComponent
  }
}

Here you can see two main differences:

  1. The inner interface is now annotated with @Component.Factory.
  2. The interface defines a single method which has the AppCompomnent as return type. The parameter is of the type you need to pass and is annotated with @BindsInstance.

In this case, the factory method contains only one parameter but it could have many. You can see the different generated code in the InitApp class where the creation of the AppCompomnent has to be like this:

class InitApp : Application() {
  - - -
  override fun onCreate() {
    super.onCreate()
    appComponent = DaggerAppComponent
      .factory() // 1
      .repository(MemoryNewsRepository()) // 2
  }
  - - -
}

As you can see, Dagger creates a factory method for you which exposes the repository() you can invoke to pass the missing dependencies. Build and run the app.

RwNews App

User selects a generic title from a list and the story displays

You’ve now covered many ways you can build dependencies in Dagger! :]

Where to Go From Here

You can download the final result using the Download Materials button at the top or bottom of this tutorial.

In this tutorial, you configured Dagger to manage DI in several ways, depending on what information you provided and how they can be used to manage dependencies, change code generation performance and runtime dependency fetching.

You’re a Dagger master now, but you still need to learn one more step: How to manage dependencies between different @Component definitions with different @Scope. You’ll learn that in the second part of this tutorial! :]

I hope you found this helpful! If you have any comments or questions, feel free to join in the forum below.