【发布时间】:2019-04-01 00:59:39
【问题描述】:
我目前的问题是我想创建一个 Helper 类来计算我的成本(存储在数据库中),以便更好地组织一切(因为我需要在我的两个活动中进行此计算)。
现在计算代码(工作正常)只是写在两个活动中(这使得一切都变得相当丑陋)。
所以:我创建了一个“CostIntervalHelper”-Class。
我把我的代码放在那里并改变了一些东西,但我现在遇到了一个大问题。为了更好地解释它,首先这里是计算方法的代码:
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;
}
现在我们来解决问题(已经在代码中放入了一些 cmets):
每当我调用该方法时,都会首先调用返回 cMonthly。 在调试模式下,我检查了一下,我可以说:在返回语句被命中后,计算就完成了(以正确的方式)。
现在我需要一个想法或示例,如何让我的代码首先(以正确的顺序)执行所有 subViewModel.getAll(Monthly/Biannually/Yearly)Costs().[...] 方法,然后点击返回语句。
我知道这有点棘手,因为我使用的是 LiveData/ViewModel,但也许有人有想法!会很棒!先谢谢了!
【问题讨论】:
标签: java android android-livedata android-jetpack