Why Dagger2 inject the same object but with 2 different instances?
Q: ArticlesContract.Presenter
is a new instance in Adapter
, which is different with ArticleListFragment
, so my data was lost ! I have no idea why I got two different instances:
@Module
public class ArticleListFragmentModule {
@Provides
ArticlesContract.Presenter provideArticlesPresenter(ArticlesPresenter presenter) {
return presenter;
}
}
public class ArticleListFragment extends DaggerFragment implements ArticlesContract.View {
@Inject
ArticlesContract.Presenter mPresenter; //one instance
}
public class ArticlesAdapter extends RecyclerView.Adapter<ArticleViewHolder> {
@Inject
ArticlesContract.Presenter mPresenter; //another different instance
}
A: scopes provide a way of telling dagger - "while this component is alive and it's scope is X then all instances scoped with X will be the same".
2018-05-16 UPDATED: this issues is fixed by following @Fred answer : lack a scope and managing this scope: Commit
@Scope
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface ArticlesScope {
}
@Module
public abstract class ActivityBuilder {
@ContributesAndroidInjector(modules = ArticleListFragmentModule.class)
@ArticleListScope
abstract ArticleListFragment bindArticleListFragment();
}
@Module
public class ArticleListFragmentModule {
/**
* Provide dependency for interface.
* Interface cannot be annotated with @Inject, otherwise it will cause, error: ArticlesContract.Presenter cannot be provided without an @Provides- or @Produces-annotated method.
*/
@Provides
@ArticleListScope
ArticlesContract.Presenter provideArticlesPresenter(ArticlesPresenter presenter) {
return presenter;
}
}
Scoping with @ContributesAndroidInjector, refer to Dagger 2 Annotations: @Binds & @ContributesAndroidInjector