In my android project, I have three MutableLiveData variables. Upon the change of their values, I want to change the value of another MutableLiveData and observe its value to make an API call. Is the process I followed a standard approach? Or are there any other good approaches?
ViewModel Code
private MutableLiveData<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);
}
Fragment Code
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();
}
});
}
I see that you've used a MediatorLiveData, but you're using it as a MutableLiveData, not making use of any of its properties. Now, you can change chemist to be a MediatorLiveData and add the other liveDatas as sources of the chemist MediatorLiveData.
in ViewModelInit:
and the same for the other two liveDatas. Then you can remove all the observers in Fragment, but the one of isAllDataReady.