1

I have been running into an issue and currently don't see a better solution.

My requirements: I have an mutable list of mutable models and I need to sum a big decimal inside the mutable model.

Here is the solution that I came up with but I'm trying to see if maybe there's a better way.

    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;
    });

And a helper class to destroy old mediator sources:

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);
        }
    }
}

If anyone can shed some light on a better solution I'd be all ears, but I may have reached a limitation of the LiveData pattern.

Note: I want to avoid using RxAndroid since LiveData seems to want to replace it. If necessary I am willing to adapt to it.

Andres S
  • 471
  • 1
  • 5
  • 19

0 Answers0