I use Dagger2 and Moxy with MVP. As I understand, Presenter can call the Repository for loading and unloading data from the database. But I just can not figure out how to create an instance of the repository: in the Activity with the help of Dagger and transfer to the presenter or in the presenter itself?
I used Repository in Activity but I think it's an anti-pattern.
It provides Context
@Module
public class AppModule {
private Context context;
public AppModule(Context context){
this.context = context;
}
@Singleton
@Provides
Context provideContext(){
return context;
}
}
This module provides Room
@Module
public class RoomModule {
@Singleton
@Provides
AppDataBase providesAppDataBase(Context context) {
return Room.databaseBuilder(context, AppDataBase.class, "budget")
.fallbackToDestructiveMigration()
.allowMainThreadQueries()
.build();
}
@Singleton
@Provides
BudgetDao providesDao(AppDataBase database) {
return database.getBudgetDao();
}
@Singleton
@Provides
DetailDao providesDetailDao(AppDataBase dataBase){
return dataBase.getDetailDao();
}
}
AppComponent
@Singleton
@Component(modules = {RoomModule.class, AppModule.class})
public interface AppComponent {
void inject(BudgetListPresenter presenter);
void inject(BudgetsActivity activity);
void inject(DetailActivity activity);
}
Repository.class
@Singleton
public class BudgetListRepository implements BudgetRepository {
private BudgetDao budgetDao;
@Inject
public BudgetListRepository(BudgetDao budgetDao){
this.budgetDao = budgetDao;
}
@Override
public void updateBudget(Budget budget) {
budgetDao.updateBudget(budget);
}
@Override
public void addBudget(Budget budget) {
budgetDao.insertBudget(budget);
}
@Override
public void deleteBudget(Budget budget) {
budgetDao.deleteBudget(budget);
}
@Override
public Budget getBudget(String id) {
return budgetDao.getBudget(id);
}
@Override
public List<Budget> getAll() {
return budgetDao.getAll();
}
}