java - Dagger with Android: How to inject context when using MVP? -


while developing android application stumbled on problem. started using dagger know basic concepts when using outside scopes of tutorials , use cases things become less clear.

so point. in application i'm using mvp described in blog post: http://antonioleiva.com/mvp-android/

so @ first injecting interactor class (the 1 handles data) presenter class , ok. implemented methods use sqlite database, there need use context in interactor class.

i can't figure out how should properly? temporary fix exclude dagger application , pass context variable in constructor when creating presenter class , interactor class inside presenter i'd use dagger.

so current application looks this.

myactivity implements myview {            mypresenter p = new mypresenter(this, getapplicationcontext()); } 

constructor inside mypresenter

mypresenter(myview view, context context) {       this.view = view;       myinteractor = new myinteractor(context); } 

and in constructor in myinteractor assign context private variable.

i need inject myinteractor mypresenter, because part of application need tested against different implementations. if possible inject mypresenter myactivity, great :)

i hope has experience i'm trying achieve :)

in class myinteractor:

public class myinteractor {      @inject     public myinteractor(context context) {        // stuff...     } } 

mypresenter-class

public class mypresenter {     @inject     myinteractor interactor;      public mypresenter(myview view) {         // perform injection. depends on dagger implementation, e.g.         objectgraph.inject(this)     } } 

for injecting context need write module provides method:

@module (injects = {mypresenter.class}) public class rootmodule {     private context context;      public rootmodule(baseapplication application) {         this.context = application.getapplicationcontext();     }      @provides     @singleton     context providecontext() {         return context;     } } 

injecting presenter-class activity not easy, because in constructor have myview-parameter, not set dagger. rethink design providing setmyview-method in mypresenter-class instead of using constructor-parameter.

edit: creating rootmodule

public class baseapplication extends application {     // store objectgraph member attribute or use wrapper-class or...      @override     public void oncreate() {         super.oncreate();         objectgraph = objectgraph.create(getinjectionmodule());     }       protected object getinjectionmodule() {         return new rootmodule(this);     } } 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -