Skip to content Skip to sidebar Skip to footer

Dagger And Mvp - Should Presenter Use Dagger For Injection

I'm starting to think in mvp, dagger should not be used in the presenter. The usual way to construct dagger is using a global component and have subcomponents for scoping the graph

Solution 1:

I also agree with the statement "Not having android related code in your presenter is always a good idea, and dagger does not interfere with that."

First, what I want to draw attention that starting from dagger version 2.10 you can use dagger.android package which simplifies injection in the activities and fragments, so you don't need to use MyApplication casting across the app.

Second, why are you not injecting WelcomePresenter into activity or fragment but vice versa?

Solution 2:

Dependency injection is useful for Android components (activities, etc.) primarily because these classes must have a no-arg constructor so the framework can construct instances of them. Any class that isn't required to have a no-arg constructor should simply receive all its dependencies in its constructor.

Edit: A side note about how you're getting a reference to the AppComponent.

Application is-a Context, and the Context returned by Context#getApplicationContext() is usually the Application instance. But this is not necessarily the case. The one place I know of where it may not be the case is in an emulator. So this cast can fail:

presenterComponent = ((MyApplication) context).getAppComponent();

Mutable static fields are evil in general, and even more so on Android. But IMO, the one place you can get away with it is in your Application class. There is only one instance of Application, and no other component will ever exist before Application#onCreate() is called. So it's acceptable to make your AppComponent a static field of MyApplication, initialize it in onCreate(), and provide a static getter, as long as you only call the getter from the lifecycle methods of other components.

Post a Comment for "Dagger And Mvp - Should Presenter Use Dagger For Injection"