2
votes

Suppose Activity have NavigationView with 3 items {timeline , profile,programs}

So we have 3 fragment

I follow MVP pattern , and each fragment have it's presenter and for DI I use Dagger2

I want inject each presenter to activity when each item click in navigation view

for each presenter I create one module and component like this

@Module()
public class FooPresenterModule {

private final FooFragment view;

public FooPresenterModule(FooFragment view) {
    this.view = view;
}

@FragmentScope
@Provides
public FooFragment provideView() {
    return view;
}
 }

and Component

@FragmentScope
@Component(modules =FooPresenterModule.class)
public interface FooPresenterInjector {

void inject(MainActivity mainActivity);

}

in Activity inject presenter by fields ->

 @Inject TimelinePresenterInjector mTimeLinePresenter;
 @Inject ProfilePresenterInjector mProfilePresenter;
 @Inject ProgramPresenterInjector mProgramPresenter;

and have 3 func for replacing fragment ->

 private void replaceTimelineFragment() {

    TimeLineFragment fragment = TimeLineFragment.newInstance();
    getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();

    DaggerTimelinePresenterInjector.builder()
            .timeLinePresenterModule(new TimeLinePresenterModule(fragment))
            .build().inject(this);

}

replace profile fragment func ->

private void replaceProfileFragment() {

    ProfileFragment fragment = ProfileFragment.newInstance();
    getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();

    DaggerProfilePresenterInjector.builder()
            .timeLinePresenterModule(new ProfilePresenterModule(fragment))
            .build().inject(this);

}

but when I rebuild project I get error

is it wrong pattern? if yes what is the best pattern for injecting different presenter in on activity?

1

1 Answers

0
votes

You are trying to "tie" dependency injection framework calls to application's business logic (i.e. perform injection when certain events happen inside your app). This is really not a good idea.

By going down this path, you will have DI logic entangled with the business logic of your app, which will make it much harder to debug and maintain it.

The "best pattern" (IMHO the only pattern) would be to perform injection just once in Activity's onCreate() method. It is not clear from your code why you want to have a reference to Fragments inside FooPresenterModule, but I strongly advice you to find a different solution for this.

One possible solution would be to inject some PresenterFactory class into Activity, and call mPresenterFactory.getPresenterForFragment(fragment) when you switch to a different fragment.

You might also want to read this post: Dependency Injection in Android.