My current problem is that I wanna create a Helper class that calculates my costs (stored in database) so that everything is organized better (because I need this calculation in two of my Activities).
Right now the calculation code (which is working fine) is just written inside the two Activities (which makes everything rather ugly).
So: I created a "CostIntervalHelper"-Class.
I put my code there and changed a few things but I am hitting a big problem right now. To explain it better, first here you go with the code of the calculation method:
public BigDecimal calculateMonthlyCosts(SubViewModel subViewModel, Context context){
//set this two times just for debugging reasons to see if the calculation actually works
cMonthly = new BigDecimal(0);
subViewModel.getAllMonthlyCosts().observe((LifecycleOwner) context, new Observer<BigDecimal>() {
@Override
public void onChanged(@Nullable BigDecimal bigDecimal) {
cMonthly = new BigDecimal(0);
if (bigDecimal != null) {
cMonthly = cMonthly.add(bigDecimal);
}
}
});
subViewModel.getAllBiannuallyCosts().observe((LifecycleOwner) context, new Observer<BigDecimal>() {
@Override
public void onChanged(@Nullable BigDecimal bigDecimal) {
cBiannually = new BigDecimal(0);
if (bigDecimal != null) {
cBiannually = cBiannually.add(bigDecimal.divide(new BigDecimal(6), 2));
}
}
});
subViewModel.getAllYearlyCosts().observe((LifecycleOwner) context, new Observer<BigDecimal>() {
@Override
public void onChanged(@Nullable BigDecimal bigDecimal) {
cYearly = new BigDecimal(0);
if (bigDecimal != null) {
cYearly = cYearly.add(bigDecimal.divide(new BigDecimal(12), 2));
cMonthly = cMonthly.add(cBiannually).add(cYearly);
}
}
});
//return is hit before the calculation so it only returns "0"
return cMonthly;
}
Now here we go with the problem (already put some comments in the code):
Whenever I call for the method, the return cMonthly is called first. In Debug-Mode I checked and I can say: AFTER the return statement was hit, the calculation gets done (in the right way).
Now I need an idea or example how I can make my code FIRST (in the right order) do all the subViewModel.getAll(Monthly/Biannually/Yearly)Costs().[...]
methods and AFTERWARDS hit the return statement.
I know this is a bit tricky because I am using LiveData/ViewModel but maybe someone has an idea! Would be awesome! Thanks ahead!