多个 MutableLiveData 更改会导致单个 MutableLiveData

问题描述 投票:0回答:1

在我的 android 项目中,我有三个 MutableLiveData 变量。在更改它们的值后,我想更改另一个 MutableLiveData 的值并观察其值以进行 API 调用。我遵循的流程是标准方法吗?或者还有其他好的办法吗?

查看模型代码

    private MediatorLiveData<ChemistEntity> chemist = new MediatorLiveData<>();
    private MutableLiveData<List<OrderPreviewRequest.LineItem>> lineItemList = new MutableLiveData<>();
    private MutableLiveData<String> paymentType = new MutableLiveData<>();
    private MutableLiveData<Boolean> isAllDataReadyForCall = new MutableLiveData<>();

public void checkAllDataReady() {
        ChemistEntity chemist = this.chemist.getValue();
        List<OrderPreviewRequest.LineItem> productListValue = this.lineItemList.getValue();
        String paymentTypeValue = this.getPaymentType().getValue();
        boolean allReady = chemist != null && productListValue != null && paymentTypeValue != null;
        isAllDataReadyForCall.postValue(allReady);
    }

片段代码

private void subscribeUiToChemist(LiveData<ChemistEntity> liveData) {
        liveData.observe(getViewLifecycleOwner(), chemist -> {
            mViewModel.checkAllDataReady();
        });
    }

    private void subscribeUiToPaymentType(LiveData<String> liveData) {
        liveData.observe(getViewLifecycleOwner(), paymentType -> {
            mViewModel.checkAllDataReady();
        });
    }

    private void subscribeUiToLineItemList(LiveData<List<OrderPreviewRequest.LineItem>> liveData) {
        liveData.observe(getViewLifecycleOwner(), lineItems -> {
            mViewModel.checkAllDataReady();
        });
    }

    private void subscribeUiToIsAllDataReady(LiveData<Boolean> liveData) {
        liveData.observe(getViewLifecycleOwner(), isReady -> {
            if(isReady) {
                mViewModel.callApi();
            }
        });
    }
java android android-livedata mutablelivedata mediatorlivedata
1个回答
0
投票

我看到您使用了 MediatorLiveData,但您将其用作 MutableLiveData,而不是使用它的任何属性。 现在,您可以将 chemist 更改为 MediatorLiveData,并将其他 liveData 添加为 chemist MediatorLiveData 的源。

private MediatorLiveData<Boolean> isAllDataReadyForCall = new MediatorLiveData<>();

在 ViewModelInit 中:

isAllDataReadyForCall.addSource(chemist, {chemist -> checkAllDataReady()})

对于其他两个 liveData 也是如此。 然后你可以删除Fragment中的所有观察者,但isAllDataReady的一个。

© www.soinside.com 2019 - 2024. All rights reserved.