网络请求失败时,LiveData不会触发两次

时间:2018-09-07 13:45:05

标签: android android-livedata mutablelivedata

当我的httprequest成功执行时,我的LiveData对象被调用了两次,但是如果发生错误,它仅被调用一次,由于自从Error验证被跳过以来,导致UI显示一个空列表。没有发出警报。

我的存储库代码

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();
}

我的BaseRepository代码

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;
}

我的片段代码

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);
        }
    });
}

最后,我的ViewModel代码

public LiveData<DataWrapper<List<Card>>> getCards(){
    return repository.loadCards();
}

总而言之,如果失败,为什么observer callback只被调用一次?因为我已经调试了它,并且在两种情况下(succefull和failure),方法asLiveData都被称为TWICE,但是只有在成功尝试中,回调函数也才被称为TWICE,在失败时{{1} }仅称为ONCE。

编辑:添加了asynctask代码

observer callback

1 个答案:

答案 0 :(得分:1)

您获得2个针对成功案例的回调并且仅对错误情形进行1次调用的原因似乎与您的存储库设置有关。

在调用loadCard时,您首先通过此调用发出数据库状态:

atomicWrapper.set(asLiveData(getCards(),null));

此时将查询您的数据库,并且当前值将触发mediatorLiveData.setValue。这将是第一发射。

mediatorLiveData.addSource(dataSource, data -> mediatorLiveData.setValue(new DataWrapper<>(data, error)));

与此同时,您触发了对您的Web服务的调用,如果调用成功,则会触发您的asynctask更新数据库。

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);

插入命令完成后,MediatorLiveData将再次触发它的setValue调用-它正在侦听数据库中的更改,因此在插入时它将收到回调。这是成功案例中的第二发射。

在错误情况下,您通过 null 作为数据源。令人惊讶的是,这不会崩溃,因为addSource方法将源参数标记为 Non Null 。由于为null,因此您不会收到回调,也不会调用mediatorLiveData.setValue。这意味着对于错误情况,您只会收到第一个发射。

如果您执行以下操作,可能会更简单:

  • 在数据库上设置一个侦听器,并在发生数据库更新时发出没有错误的数据值。

  • 在收到错误后,您可以发出带有错误的DataWrapper

例如像这样:

    private final AtomicBoolean isLoading = new AtomicBoolean(false);
    private final MediatorLiveData<DataWrapper<List<Card>>> mediatorLiveData = new MediatorLiveData<>();

    private MyRepository() {
        // requires a cardsDao
        // listen for DB changes and emit on callback
        mediatorLiveData.addSource(cardsDao.getCards(), data -> mediatorLiveData.setValue(new DataWrapper<>(data, null)));
    }

    public LiveData<DataWrapper<List<Card>>> cardsData() {
        return mediatorLiveData;
    }

    public void loadCards() {
        if (!isLoading.get()) {
            isLoading.set(true);
            webService.getCards(result -> {
                CardResponse res = (CardResponse) result;
                List<Card> cardList = res.getCardsList();
                // Trigger update in db
                getInsertAsyncTask.execute(cardList.toArray(new Card[cardList.size()]));
                isLoading.set(false);
            }, error -> {
                // Emit the error
                mediatorLiveData.setValue(new DataWrapper<>(null, error.getMessage()));
                isLoading.set(false);
            }, TAG);
        }
    }