My LiveData
object is called twice when my httprequest is succefull, but in case of an error, it's only called once, causing the UI to display an empty list since my Error
verification was skipped since there was no alert fired.
My repository code
private LiveData<List<Card>> getCards() {
return cardsDao.getCards();
}
// Network request, that deals with the success or error of the request
public LiveData<DataWrapper<List<Card>>> loadCards() {
AtomicReference<LiveData<DataWrapper<List<Card>>>> atomicWrapper = new AtomicReference<>();
if (getCards().getValue() == null) {
webService.getCards(result -> {
CardResponse res = (CardResponse) result;
List<Card> cardList = res.getCardsList();
getInsertAsyncTask.execute(cardList.toArray(new Card[cardList.size()]));
}, error -> {
atomicWrapper.set(asLiveData(null, error.getMessage()));
}, TAG);
}
atomicWrapper.set(asLiveData(getCards(),null));
return atomicWrapper.get();
}
My BaseRepository code
LiveData<DataWrapper<List<T>>> asLiveData(LiveData<List<T>> dataSource, String error) {
MediatorLiveData<DataWrapper<List<T>>> mediatorLiveData = new MediatorLiveData<>();
mediatorLiveData.addSource(dataSource, data -> mediatorLiveData.setValue(new DataWrapper<>(data, error)));
return mediatorLiveData;
}
My Fragment code
private void subscribeToCards() {
mViewModel.getCards().observe(this, listDataWrapper -> {
if( listDataWrapper == null ) {
return;
}
if( listDataWrapper.error != null) {
// Show error on UI
dismissProgress();
Log.e(TAG, "Error - " + listDataWrapper.error);
showError(getString(R.string.cards_error_get_list_message));
EventBus.getDefault().post(new DialogMessageEvent(getString(R.string.cards_error_get_list_title),
getString(R.string.cards_error_get_list_message), getString(R.string.cards_error_get_list_button)));
}
if( listDataWrapper.data != null ) {
// Update Ui
refreshCardsList(listDataWrapper.data);
cardsViewVisibility(true);
}
});
}
And finally, my ViewModel code
public LiveData<DataWrapper<List<Card>>> getCards(){
return repository.loadCards();
}
To summarize, in case of failure, why does the observer callback
only gets called once ? Because I've debug it, and in both ( succefull and failure ) cases, the method asLiveData
is called TWICE, but it's only in the succefull attempt that the callback is called TWICE aswell, on failure the observer callback
it's only called ONCE.
Edit: Added asynctask code
@SuppressLint("StaticFieldLeak")
AsyncTask<T,Void,Void> getInsertAsyncTask = new AsyncTask<T, Void, Void>() {
@Override
protected Void doInBackground(T... ts) {
daoObject.insertObjects(Arrays.asList(ts));
return null;
}
};