Reputation: 6972
I have recently studied about Retrofit. I am just implementing in my project. I have almost 20 plus api. I have declared all the methods like.
public interface RF_Calls {
@POST(AppConstants.API_EVENTS_BYSTUDENTS)
void getEvents(@Body JsonObject events);
@POST(AppConstants.API_EXAMS_BYSTUDENTS)
void getExamsbyStudents(@Body JsonObject exams);
}
I just want a common progressbar for both the methods which has to dismissed once it get success and failure
Upvotes: 1
Views: 3101
Reputation: 3397
What you want to do first is make the interface call correct, it should be (as of retrofit 2):
Call<object> getEvents(@Body JsonObject events)
**
**Note that the object
type parameter should be replace with a model that you expect to be returned from the service. If you don't care about the response, you could leave it as object I believe.
This will allow an async call to be made and you can give it a callback:
//This should be in your activity or fragment
final RF_Calls service = //Create your service;
Call c = service.getEvents(json);
[Your progress view].show();
c.enqueue(new Callback<object>{
@Override
public void onResponse(Response<object>, Retrofit retrofit){
[Your progress view].hide();
}
@Override
public void onFailure(Throwable t){
[Your progress view].hide();
}
});
The progress screen is a UI concern so it should be handled in an activity or fragment, the said activity or fragment will make use of the services to get the data it needs.
In response to the comment, a simple solution that wraps the calls:
//Defines an interface that we can call into
public interface Act<T> {
void execute(T data);
}
//Makes a call to the service and handles the UI manipulation for you
public static <T> void makeServiceCallWithProgress(Call c, final Act<T> success, final Act<Throwable> failure, final ProgressBar progressBar) {
progressBar.setVisibility(View.VISIBLE);
c.enqueue(new Callback<T>() {
@Override
public void onResponse(Response<T> response, Retrofit retrofit) {
progressBar.setVisibility(View.GONE);
success.execute(response.body());
}
@Override
public void onFailure(Throwable t) {
progressBar.setVisibility(View.GONE);
failure.execute(t);
}
});
}
Here is an example usage:
makeServiceCallWithProgress(service.getEvents(json),
new Act<MyResponseModel>() {
@Override
public void execute(MyResponseModel data) {
//TODO: Do something!
}
},
new Act<Throwable>() {
@Override
public void execute(Throwable data) {
//TODO: Do something!
}
},
progressBar);
It isn't the prettiest, but then again, the version of Java Android uses doesn't give us much for functions be first-class citizens.
Upvotes: 6