Search code examples
androiddagger-2android-mvp

(Dagger 2) Provide same instance for different types in MVP


I'm following MVP pattern in my application. I have a view which extends another abstract view class, implements another interface (say A) and also implements View contract (say B) in MVP. I want to have a same instance in dependency graph when I ask for types A and B. How can I achieve that ?

In short:

class MyAbstractView implements MyInterface {

}

class MyView extends MyAbstractView implements MyViewContract {

}

@Module
class MyModule {
    @Provides
    MyInterface provideMyInterface() {
     return new MyView();
    }

    @Provides
    MyViewContract provideMyViewContract() {
       // I cannot call provideMyInterface() and return here
       // but I want to return the same MyView instance
       // ????
   }
}

Note: I dont want to have MyView and persist it in the @Module!!


Solution

  • You can use constructor injection along with the @Binds annotation in your module to achieve this. Simply add a constructor and annotate it with @Inject in MyView. You can then mark MyView as @Singleton so that the same instance is used everywhere(assuming the component is also scoped with @Singleton).

    @Singleton
    class MyView extends MyAbstractView implements MyViewContract {
        @Inject
        public MyView() {}
    }
    
    @Module
    abstract class MyModule {
        @Binds
        abstract MyInterface provideMyInterface(MyView myView);
    
        @Binds
        abstract MyViewContract provideMyViewContract(MyView myView);
    }