How to dismiss progress bar from repository?

Viewed 854

I am using MVVM pattern with repository for network call.

When i click button in my view it triggers save/ fetch data method in my viewmodel which then make call to repository wherein i am doing my network operation using Retrofit.

Now i would like to dismiss my progress bar with proper message (like saved, error etc. from my repository (onResponse or onFailure) that i started inside view.

  public void onClick(View v) {
            ProgressDialog dialog = new ProgressDialog(getActivity());
            dialog.setMessage("saving...");
            dialog.show();
            cuttingUnitViewModel.saveProjectUnit();
        }

Is it ok to do what i am doing or is there better alternative?

All i want to say that I want to return NETWORK STATE and DATA both from repository , how to do that?

2 Answers

Main issue which I think in your case is that you initiate a call and get its response but your activity doesn't get to know any of these changes. Without this you might have to create some custom util classes or some other workaround which in my opinion would be a really bad practice.

My suggestion is that you create a MutableLiveData object for your response in your activity's ViewModel, then pass this object to your repository so that when your retrofit completes your call you can post the result on your livedata object.

And in your activity you should be observing this livedata for changes. So, when you get the result and post the new value, then in activity livedata observer's onChanged() you can get the result and even make your progress bar disappear.

Sorry, if this was too hard to understand. Here is a nice little tutorial you can refer to. I suppose that would make things easier with an example. Good luck!

No, it is not proper to do View activities like dismissing ProgressBar in the Repository as this class is only meant to deal with Data from different sources and this creates tight coupling. A proper design would be to set callback functions back to the class where the View is present from the Repository class through the intermediate layers like ViewModel until it reaches the View layer and then dismiss the ProgressBar there.

Related