I want to build an Android app using the MVP pattern.
I have a fragment (the view) and a presenter class.
What I want is to basically inject the presenter into the fragment, and set the fragment as the presenter's view (via an interface that the view will implement)
How can I easily and correctly connect the 2 using dependency injection (with Dagger2)?
Edit:
In addition, I'd like the presenter to be a singleton, so it will be able to persist data & state across orientation changes
First you need to define a presenter module:
@Module
class SearchPresenterModule {
@NonNull
private final SearchContract.View mView;
SearchPresenterModule(@NonNull SearchContract.View view) {
this.mView = view;
}
@Provides
SearchContract.View provideSearchContractView() {
return mView;
}
}
Here's the example component:
@FragmentScoped
@Component(modules = SearchPresenterModule.class)
interface SearchComponent {
void inject(SearchActivity activity);
}
And inject your presenter:
@Inject
SearchPresenter mSearchPresenter;
DaggerSearchComponent.builder()
.searchPresenterModule(new SearchPresenterModule(searchFragment))
.build()
.inject(this);
Finally inject your presenter's constructor:
@Inject
SearchPresenter(@NonNull SearchContract.View view, @NonNull SearchRepository searchRepository) {
this.mView = view;
mView.setPresenter(this);
}
Extra: Here's fragmentscoped annotation:
@Documented
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface FragmentScoped {
}
You can check my example repo for MVP + DAGGER2 https://github.com/savepopulation/wikilight
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With