Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a Presenter into a View (MVP pattern) using Dagger2

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

like image 771
dors Avatar asked Aug 11 '15 22:08

dors


1 Answers

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

like image 154
savepopulation Avatar answered Oct 18 '22 08:10

savepopulation