使用Android Live数据聚合字段

使用Android Live数据聚合字段,android,mvvm,android-livedata,Android,Mvvm,Android Livedata,我遇到了一个问题,目前没有更好的解决方案 我的要求:我有一个可变模型的可变列表,我需要在可变模型中加一个大的小数 这是我提出的解决方案,但我正在尝试看看是否有更好的方法 MyMediatorLiveData<BigDecimal> totalMediator = new MyMediatorLiveData<>(); this.totalHours = Transformations.switchMap(records, input -> {

我遇到了一个问题,目前没有更好的解决方案

我的要求:我有一个可变模型的可变列表,我需要在可变模型中加一个大的小数

这是我提出的解决方案,但我正在尝试看看是否有更好的方法

    MyMediatorLiveData<BigDecimal> totalMediator = new MyMediatorLiveData<>();
    this.totalHours = Transformations.switchMap(records, input -> {
        totalMediator.removeAllSources();
        Map<String, BigDecimal> totals = new HashMap<>();
        for (LiveData<Record> record : input) {
            totalMediator.addSource(record, model -> {
                if (model != null) {
                    totals.put(model.getKey(), model.getTotal());

                    BigDecimal total = BigDecimal.ZERO;
                    for (BigDecimal recordTotal : totals.values()) {
                        total = total.add(recordTotal);
                    }
                    totalMediator.setValue(total);
                }
            });
        }
        return totalMediator;
    });
MyMediatorLiveData totalMediator=newmymediatorlivedata();
this.totalHours=Transformations.switchMap(记录,输入->{
totalMediator.removeAllSources();
Map totals=新的HashMap();
for(LiveData记录:输入){
totalMediator.addSource(记录,型号->{
如果(型号!=null){
totals.put(model.getKey(),model.getTotal());
BigDecimal总计=BigDecimal.0;
for(BigDecimal recordTotal:totals.values()){
总计=总计。添加(记录总计);
}
totalMediator.setValue(总计);
}
});
}
返回总调解人;
});
和用于销毁旧中介源的帮助器类:

public class MyMediatorLiveData<T> extends MediatorLiveData<T> {
    private List<LiveData<?>> addedSources = new ArrayList<>();

    @Override
    public <S> void addSource(@NonNull LiveData<S> source, @NonNull Observer<? super S> onChanged) {
        super.addSource(source, onChanged);
        addedSources.add(source);
    }

    public void removeAllSources() {
        for (LiveData<?> source : addedSources) {
            removeSource(source);
        }
    }
}
公共类MyMediatorLiveData扩展了MediatorLiveData{

私人列表看起来与中表达的想法类似,不知是否有用与中表达的想法类似,不知是否有用