Home > Net >  Why I'm not able to retry API call in my existing MVVM architecture in Android?
Why I'm not able to retry API call in my existing MVVM architecture in Android?

Time:03-15

There are many answers there, but none of is fitting into my problem!

Inside Activity:

setObservers() is calling from onCreate()

private void setObservers() {
        showProgressDialog();
        viewModel.getReviewData().observe(this, reviewResponseResource -> {
            dismissProgressDialog();
            switch (reviewResponseResource.getStatus()) {
                case SUCCESS:
                    if (reviewResponseResource.getData() != null) {
                        ReviewResponse reviewResponse = reviewResponseResource.getData();
                        if (!AppUtils.isNull(reviewResponse)) {
                            setReviewData(reviewResponse.getData());
                        }
                    }
                    break;

                case ERROR:
                    showErrorSnackBarLayout(reviewResponseResource.getCode(), reviewResponseResource.getMessage(), new IRetryListener() {
                        @Override
                        public void retry() {
                            //TODO retry
                        }
                    });
                    break;
            }
        });
    }

As you can see, I added TODO, I tried to put this: viewModel.getReviewData() but not getting any callback

Viewmodel:

val reviewData = liveData(Dispatchers.IO) {
        emit(repository.getReviewResponse())
    }

CodePudding user response:

I think I see the problem. Your reviewData property creates a LiveData once at property initialization time. If you repeatedly call this property, it will keep returning the same LiveData instance, so it will not call repository.getReviewResponse() again when you repeatedly call the property.

You could change the property to have a custom getter that starts a new liveData() call each time you retrieve it, but I don't think this is a good idea because it creates an "astonishing" property that has a side effect and returns a different object every time it is accessed.

I would change the property into a function like this:

    fun fetchReviewData() = liveData(Dispatchers.IO) {
        emit(repository.getReviewResponse())
    }

By the way, I think you probably want to put setObservers() instead of viewModel.getReviewData() at your TODO so it will show the progress dialog again.

CodePudding user response:

Solution1 : if you looking for manual retry , you should tap on retry button as you did follow so retry api call.

solution2 : you should implement retry auto call back like this example- https://androidwave.com/retrying-request-with-retrofit-android/ or try your own logic after get fail api call if fail try max limit put retry logic

  • Related