Livedata数学运算 [英] Livedata mathematical operations

查看:65
本文介绍了Livedata数学运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个实时数据.我需要对它们进行减法运算,但是如何使用两个livedata来实现呢?

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 refresh result always when I need it.

       totalFragmentViewModel.getTotalExpenseValue().observe(getViewLifecycleOwner(), new Observer<Double>() {
        @Override
        public void onChanged(Double aDouble) {
            expenseTextView.setText(String.valueOf(aDouble));
            mExpense += aDouble;
            balanceTextView.setText(String.valueOf(mIncome - mExpense));
        }
    });

    totalFragmentViewModel.getTotalIncomeValue().observe(getViewLifecycleOwner(), new Observer<Double>() {
        @Override
        public void onChanged(Double aDouble) {
            incomeTextView.setText(String.valueOf(aDouble));
            mIncome += aDouble;
            balanceTextView.setText(String.valueOf(mIncome - mExpense));
        }
    });

推荐答案

您可以使用 MediatorLiveData 聚合多个源.在您的情况下,这将是 change事件的汇总(数据将被忽略),例如,您的视图模型可能是这样实现的:

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:

class MyViewModel extends ViewModel {
    private MutableLiveData<Double> expense = new MutableLiveData<>();
    private MutableLiveData<Double> income = new MutableLiveData<>();
    private MediatorLiveData<Double> balance = new MediatorLiveData<>();

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

    @AnyThread
    public void updateExpense(Double value) {
        expense.postValue(value);
    } 

    @AnyThread
    public void updateIncome(Double value) {
        income.postValue(value);
    }

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

    // argument is ignored because we don't know expense it or it is income
    private void onChanged(@SuppressWarnings("unused") Double ignored) {
        Double in = income.getValue(), ex = expense.getValue();
        // correct value or throw exception if appropriate
        if (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);
    }
}

这篇关于Livedata数学运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆