Skip to content

Instantly share code, notes, and snippets.

@ggrell
Forked from arkivanov/DaggerParentChildExample.kt
Created October 31, 2020 18:18
Show Gist options
  • Save ggrell/e039203a839e6f8fe4bf2a0f3beba619 to your computer and use it in GitHub Desktop.
Save ggrell/e039203a839e6f8fe4bf2a0f3beba619 to your computer and use it in GitHub Desktop.
Dagger parent-child example
// Deps
interface Database
interface Network
// Child
interface ChildRepository
class Child(dependencies: Dependencies) {
interface Dependencies {
val database: Database
val network: Network
val repository: ChildRepository
}
}
// Parent
class Parent(dependencies: Dependencies) {
init {
val component = DaggerParentComponent.factory().create(dependencies)
val child = component.child() // Get the Child
}
interface Dependencies {
val database: Database
val network: Network
}
}
internal class ChildRepositoryImpl : ChildRepository
@Module
internal class ParentModule {
@Provides
fun childRepository(): ChildRepository = ChildRepositoryImpl()
@Provides
fun child(component: ParentComponent): Child = Child(component)
}
@Component(
modules = [ParentModule::class],
dependencies = [Parent.Dependencies::class]
)
internal interface ParentComponent : Child.Dependencies {
fun child(): Child
@Component.Factory
interface Factory {
fun create(
dependencies: Parent.Dependencies
): ParentComponent
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment