Skip to content

Instantly share code, notes, and snippets.

@kgmyshin
Last active October 26, 2018 02:13
Show Gist options
  • Save kgmyshin/ce248cbde5d74c8dc4cc61bf6a7ac3be to your computer and use it in GitHub Desktop.
Save kgmyshin/ce248cbde5d74c8dc4cc61bf6a7ac3be to your computer and use it in GitHub Desktop.
マルチモジュール時のDagger-AndroidでのInject
import android.app.Activity
import androidx.fragment.app.Fragment
import dagger.android.DispatchingAndroidInjector
import javax.inject.Inject
class AppInjector : HasDispatchingFragmentInjector {
@Inject
lateinit var supportFragmentInjector: DispatchingAndroidInjector<Fragment>
override fun dispatchingFragmentInjector(): DispatchingAndroidInjector<Fragment> = supportFragmentInjector
}
interface HasDispatchingFragmentInjector {
fun dispatchingFragmentInjector(): DispatchingAndroidInjector<Fragment>
}
import androidx.fragment.app.Fragment
import dagger.android.AndroidInjector
class ModuleFragmentInjector : AndroidInjector<Fragment> {
private val injectorList = mutableListOf<HasDispatchingFragmentInjector>()
fun addInjector(injector: HasDispatchingFragmentInjector) {
injectorList.add(injector)
}
override fun inject(instance: Fragment) {
val wasInjected = injectorList.any { it.dispatchingFragmentInjector().maybeInject(instance) }
if (!wasInjected) {
throw IllegalArgumentException("injection failed")
}
}
}
class MyApplication : Application(), HasSupportFragmentInjector, HasActivityInjector {
private val moduleFragmentInjector = ModuleFragmentInjector()
override fun supportFragmentInjector(): AndroidInjector<Fragment> = moduleFragmentInjector
override fun onCreate() {
super.onCreate()
// OtherModule用のInjectorとComponent作成
val otherModuleInjector = OtherModuleInjector()
DaggerOtherModuleComponent.builder()
...
.build()
.injewct(otherModuleInjector)
// AppModule用のInjectorとComponent作成
val appInjector = AppInjector()
DaggerAppComponent.builder()
...
.inject(appInjector)
moduleFragmentInjector.addInjector(otherModuleInjector)
moduleFragmentInjector.addInjector(appInjector)
}
}
import android.app.Activity
import androidx.fragment.app.Fragment
import dagger.android.DispatchingAndroidInjector
import javax.inject.Inject
class OtherModuleInjector : HasDispatchingFragmentInjector {
@Inject
lateinit var supportFragmentInjector: DispatchingAndroidInjector<Fragment>
override fun dispatchingFragmentInjector(): DispatchingAndroidInjector<Fragment> = supportFragmentInjector
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment