Description
Injecting presenters using Dagger reduces null checks and setPresenter() methods. Whenever an activity is used, Dagger couples the view with the Presenter. Which ultimately results into clearer code.
Example
We created a simple MVP login Application.
The ViewUserModule provides the ViewUserComponent with the ViewUserPresenter.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Module | |
public class ViewUserModule { | |
private ViewUsersView viewUsersView; | |
public ViewUserModule(ViewUsersView viewUsersView) { | |
this.viewUsersView = viewUsersView; | |
} | |
@ViewUserScope | |
@Provides | |
ViewUsersView provideViewUsersView() { | |
return viewUsersView; | |
} | |
@ViewUserScope | |
@Provides | |
ViewUserPresenter provideViewUserPresenter(ViewUserInteractor viewUserInteractor) { | |
return new ViewUserPresenter(viewUsersView, viewUserInteractor); | |
} | |
} |
This ViewUserPresenter gets initialized with the viewUsersView. Which is added when the module is instantiated.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Override | |
protected void setupComponent() { | |
MVPLoginApplication.get(this) | |
.getAuthComponent() | |
.plus(new ViewUserModule(this)) | |
.inject(this); | |
} |
Which happens in the viewUsersActivity. So whenever a new Presenter is created, the Presenter always has a relationship with a view. So this is never null.
Check out the Github page to view the complete repository.