I have some Group module with MVP pattern.I just started to learn Dagger2 and I expect GroupComponent to inject repository into presenter, and provide presenter for GroupFragment.
There is my Repository:
public class GroupServerRepository {
@Inject
public GroupServerRepository(){}
my Presenter:
public class GroupPresenter implements LifecycleObserver {
private GroupServerRepository repository;
@Inject
public GroupPresenter(GroupServerRepository repository){
this.repository = repository;
}
Component:
@Component
interface GroupComponent{
GroupPresenter getPresenter();
GroupServerRepository getRepository();
}
Fragment:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_group, container, false);
GroupContracts.GroupComponent component =
DaggerGroupContracts_GroupComponent.create();
presenter = component.getPresenter();
So i expect to have next code in generated component class:
@Override
public GroupPresenter getPresenter() {
return new GroupPresenter(getRepository());
}
@Override
public GroupServerRepository getRepository() {
return new GroupServerRepository();
}
But instead of this, i have next one:
@Override
public GroupPresenter getPresenter() {
return new GroupPresenter(new GroupServerRepository());
}
@Override
public GroupServerRepository getRepository() {
return new GroupServerRepository();
}
I tried to rebuild the project but i didn't help.
Like Jannik noted there is a scoping problem. Every time when you just use @Inject or @Provides a new instance will be created. You need to have some Scope. There is scope out of the box for you which is @Singleton, but it is not what you need. You need custom scopes like:
@ActivityScope
@FragmentScope
and etc.
Here is an example:
You can check the project itself which is a great example for right usage of Dagger2.
https://github.com/google/iosched
Here is an article about the app:
https://medium.com/@JoseAlcerreca
But read something how scopes work.
https://proandroiddev.com/dagger-2-component-relationships-custom-scopes-8d7e05e70a37