Skip to content Skip to sidebar Skip to footer

Livedata Mathematical Operations

I have two livedatas. I need to take subtraction on them, but how to do it with two livedatas? I've created something like this, but this is no proper way because it doesn't refres

Solution 1:

You can use MediatorLiveData to aggregate multiple sources. In your case it will be aggregation of change events (data will be ignored), e.g, your view model might be implemented like this:

classMyViewModelextendsViewModel {
    private MutableLiveData<Double> expense = newMutableLiveData<>();
    private MutableLiveData<Double> income = newMutableLiveData<>();
    private MediatorLiveData<Double> balance = newMediatorLiveData<>();

    publicMyViewModel() {
        // observe changes of expense and income
        balance.addSource(expense, this::onChanged);
        balance.addSource(income, this::onChanged);
    }

    @AnyThreadpublicvoidupdateExpense(Double value) {
        expense.postValue(value);
    } 

    @AnyThreadpublicvoidupdateIncome(Double value) {
        income.postValue(value);
    }

    // expose balance as LiveData if you want only observe itpublic LiveData<Double> getBalance() {
        return balance;
    }

    // argument is ignored because we don't know expense it or it is incomeprivatevoidonChanged(@SuppressWarnings("unused") Double ignored) {
        Doublein= income.getValue(), ex = expense.getValue();
        // correct value or throw exception if appropriateif (in == null)
            in = 0.0;
        if (ex == null)
            ex = 0.0;
        // observer works on the main thread, we can use setValue() method// => avoid heavy calculations
        balance.setValue(in - ex);
    }
}

Solution 2:

Try this:

totalFragmentViewModel.getTotalExpenseValue().observe(getViewLifecycleOwner(), newObserver<Double>() {
    @OverridepublicvoidonChanged(Double expense) {

        expenseTextView.setText(String.valueOf(expense));
        mExpense += expense;

        totalFragmentViewModel.getTotalIncomeValue().observe(getViewLifecycleOwner(), newObserver<Double>() {
        @OverridepublicvoidonChanged(Double income) {
            incomeTextView.setText(String.valueOf(income));
            mIncome += income;
            balanceTextView.setText(String.valueOf(mIncome - mExpense));
        }
    });
    }
});

Post a Comment for "Livedata Mathematical Operations"