Search code examples
androidkotlinmoduleinterfacedagger-2

android - Dagger 2 injecting multiple interface and the implementation class


So i want to build multi modular android project and have a problem with injecting the interface and the implementation.

I have two interface for navigation between fragment

first interface

interface Fragment1Navigation {

    fun navigateToFragment1()
    fun navigateToFragment2()

}

second interface

interface Fragment2Navigation {

    fun navigateToFragment3()
    fun navigateToFragment4()

}

then i have the class that implement those two interfaces

class Navigator: BaseNavigator(), Fragment1Navigation, Fragment2Navigation {

    override fun navigateToFragment1() {
        // some implementation
    }

    override fun navigateToFragment2() {
        // some implementation
    }

    override fun navigateToFragment3() {
        // some implementation
    }

    override fun navigateToFragment4() {
        // some implementation
    }


}

i want to inject this Navigator class in my mainActivity to bind my navcontroller first and also i want to inject the interface in other fragment and i made the module class like this

@Module()
class NavigationModule {

    @Provides
    @Singleton
    fun provideNavigator(): Navigator = Navigator()

    @Provides
    fun provideFragment1Navigation(): Fragment1Navigation = Navigator()

    @Provides
    fun provideFragment2Navigation(): Fragment2Navigation = Navigator()
}

I want those provideFragmentNavigation and provideNavigatioin to provide the same Navigator() so interface in fragment lead to same navigator like in main activity, but turns out it provide different instance so the interface in fragment lead to different navigator from mainactivity


Solution

  • Two ways u can achieve this:

    • using @Binds instead of @Provides
    • passing the Navigation() object directly to the constructor of NavigationModule

    using binds

    class Navigator @Inject constructor(): BaseNavigator(), Fragment1Navigation, Fragment2Navigation { 
    
        // body
    }
    

    Module

    @Module()
    abstract class NavigationModule {
    
        @Binds
        abstract fun provideNavigator(navigator: Navigator): BaseNavigator
    
        @Binds
        abstract fun provideFragment1Navigation(navigator: Navigator): Fragment1Navigation 
    
        @Binds
        abstract fun provideFragment2Navigation(navigator: Navigator): Fragment2Navigation
    }