LoginSignup
3
4

More than 3 years have passed since last update.

@Component.Builderの代わりに@Component.Factoryを使う

Last updated at Posted at 2019-06-08

概要

ApplicationのContextをインジェクトしたい場合、Moduleのコンストラクタの引数にとるか、Component.Builderを定義していましたが、Dagger2.22から @Component.Builder AndroidInjector.Builderがdeprecatedになったので対応メモ。

@Component.Factory

@Component.Builderに加えて@Component.Factoryが追加されました。

今までは

@Component(...)
interface ApplicationComponent {

   @Component.Builder
   interface Builder {
        @BindsInstance
        fun context(context: Context): Builder

        fun build(): ApplicationComponent
   }
}

あるいはdagger-androidを使っている場合は

@Component(...)
interface ApplicationComponent : AndroidInjector<MyApp> {

   @Component.Builder
   abstract class Builder : AndroidInjector.Builder<MyApp>
}

の様に書いていました。
@Component.Factoryを使った場合はcreateメソッドを一つだけ定義するようにします。
そのため、@BindsInstanceアノテーションがメソッドの引数に指定できるようになりました。

@Component(...)
interface ApplicationComponent {

   @Component.Factory
   interface Factory {
        fun create(@BindsInstance context: Context): ApplicationComponent
   }
}

dagger-androidを使う場合は

@Component(...)
interface ApplicationComponent : AndroidInjector<MyApp> {

   @Component.Factory
   interface Factory : AndroidInjector.Factory<MyApp>
}

のようになります。
他にもBindsInstanceしたいものがあった場合などにはcreateの引数に取れば良さそう。
なので、Builderと比べて、オブジェクトの渡し忘れがコンパイルで検知されるので、ミスが減りそうです。

以上!

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4