Retrofit ProgressBar

I recently studied Retrofit. I just implement in my project. I have almost 20 plus api. I prescribed all such methods.

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 need a general level of progress for both methods that should be fired after success and failure

+4
source share
1 answer

What you want to do first is to configure the interface correctly, it should be (in terms of modification 2): Call<object> getEvents(@Body JsonObject events)**

** Please note that the type parameter objectshould be replaced with the model that you expect to receive from the service. If you don’t care about the answer, you can leave it as an object that I consider.

, :

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

- , , .


, :

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

:

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

, , Java Android , .

+4

Source: https://habr.com/ru/post/1625521/


All Articles