1- Create your Scope
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Scope;
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface BaseScope {
}
2- Create your contract
public interface FeatureContract {
interface View {
void onReceiveError(Throwable throwable);
void onReceiveItems(List<Object> items);
void showAlertDialog();
... //others methods
}
interface Presenter {
void onInitView(Object item);
}
}
3- Create your module (dagger2)
import dagger.Module;
import dagger.Provides;
@Module
public class FeatureContractModule {
private final FeatureContract.View mView;
public FeatureContractModule(FeatureContract.View view) {
mView = view;
}
@Provides @BaseScope
FeatureContract.Presenter providesFeaturePresenter(FeatureContract.View view) {
return new FeaturePresenter(view);
}
@Provides @BaseScope
FeatureContract.View providesFeatureView() {
return mView;
}
}
4- Create your presenter
public class FeaturePresenter implements FeatureContract.Presenter{
@NonNull
private final FeatureContract.View mView;
public FeaturePresenter(@NonNull FeatureContract.View view){
mView = view;
}
@Override
public void onInitView(Object item){
mView.showAlertDialog(); //<--for sample
}
}
5- In your Fragment
import javax.inject.Inject;
public class FeatureFragment extends Fragment implements FeatureContract.View{
@Inject FeatureContract.Presenter mPresenter;
@Override public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
((MyApplication) getActivity().getApplication()).getDataComponent()
.plus(new FeatureContractModule(this /*view*/))
.inject(this /*fragment*/);
mPresenter. onInitView(null);
}
}
5- Your Application
public class MyApplication extends Application {
//Dagger object
private DataComponent mDataComponent;
/**
* Dagger Injector
*/
public static DataComponent get(Context context) {
MyApplication application = (MyApplication) context.getApplicationContext();
return application.mDataComponent;
}
@Override
public void onCreate() {
super.onCreate();
mDataComponent = DaggerDataComponent.builder()
.dataModule(new DataModule(this, Locale.getDefault()))
.build();
}
public DataComponent getDataComponent() {
return mDataComponent;
}
}
6 - Create DataComponent
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = {DataModule.class})
public interface DataComponent {
Application application();
FeatureComponent plus(FeatureContractModule module);
...
}
7 - Finally your ComponentModule
import dagger.Module;
import dagger.Provides;
@BaseScope
@Subcomponent(modules = FeatureContractModule.class)
public interface FeatureComponent {
void inject(FeatureFragment fragment);
}
I believe I have not forgotten anything