Skip to content

Instantly share code, notes, and snippets.

@arkivanov
Created October 14, 2020 15:50
Show Gist options
  • Select an option

  • Save arkivanov/3d38bd0d4c7c5dbdf7890764ad29028a to your computer and use it in GitHub Desktop.

Select an option

Save arkivanov/3d38bd0d4c7c5dbdf7890764ad29028a to your computer and use it in GitHub Desktop.

Revisions

  1. arkivanov created this gist Oct 14, 2020.
    58 changes: 58 additions & 0 deletions DaggerParentChildExample.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    // 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
    }
    }