Skip to content

Instantly share code, notes, and snippets.

@LuigiPapino
Created February 2, 2018 08:59
Show Gist options
  • Save LuigiPapino/e0ecb78d61488032fca8fb9a9aa1f053 to your computer and use it in GitHub Desktop.
Save LuigiPapino/e0ecb78d61488032fca8fb9a9aa1f053 to your computer and use it in GitHub Desktop.
Modular Architecture - Dagger2 - BaseInjector
@Singleton
@Component(modules = arrayOf(NetworkModule::class, RepositoryModule::class))
interface ApplicationComponent : AndroidInjector<MyApplication> {
fun networkSubComponentBuilder(): NetworkSubComponent.Builder;
fun repositorySubComponentBuilder(): RepositorySubComponent.Builder;
}
/**
* BaseInjector for any class that can provide an Application instance
**/
interface BaseInjector<T : BaseApplicationProvider> : AndroidInjector<T> {
abstract class Builder<T : BaseApplicationProvider> : dagger.android.AndroidInjector.Builder<T>() {
//declare dependency to BaseSubComponent
abstract fun plus(component: BaseSubComponent): Builder<T>
fun inject(activity: T) {
//retrieve BaseSubComponent instance
plus(activity.baseApplication.provideBaseSubComponent())
//create and inject activity/fragment/service
create(activity)
.inject(activity)
}
}
}
@Subcomponent
interface BaseSubComponent : RepositorySubComponent, NetworkSubComponent {
@dagger.Subcomponent.Builder
interface Builder {
fun build(): BaseSubComponent
}
}
class BrowserActivity() : BaseApplicationProvider {
override val baseApplication: BaseApplication
get() = application as BaseApplication
}
class BaseApplication() : Application {
fun provideBaseSubComponent() = applicationComponent.baseSubComponentBuilder().build()
}
@BrowserScope
@Component(modules = arrayOf(BrowserModule::class),
dependencies = arrayOf(BaseSubComponent::class))
interface RecipeBrowserFragmentComponent : BaseInjector<BrowserActivity> {
@Component.Builder
abstract class Builder : BaseInjector.Builder<BrowserActivity>()
}
@Subcomponent
interface RepositorySubComponent {
val sharedPref: SharedPref
val userRepository: UserRepository
@Subcomponent.Builder
interface Builder {
fun build(): RepositorySubComponent
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment