8

I am using Retrofit 2.4.0 to send requests to a server. But sometimes server blocking my request if it has a similar timestamp in milliseconds with another request. I need to send request one at a time:

  1. Request A is sent
  2. Request B waits until the response for Request A received
  3. Request A completes with success or error
  4. Request B is sent

Is it possible to create such queue with Retrofit and OkHttp libraries?

Joe Rakhimov
  • 4,713
  • 9
  • 51
  • 109
  • Take a look at this https://stackoverflow.com/a/46210009/2837971 and this could be more helpful https://stackoverflow.com/a/48497070/2837971 – b2mob Aug 24 '18 at 06:01
  • you can use asyntask for your requirement or the issue occurring using httpurlconnectionclass – Quick learner Aug 24 '18 at 06:10
  • Use RxJava for Sync calls https://stackoverflow.com/questions/35062485/rxjava-how-to-emit-observables-synchronously – Chetan Shelake Aug 24 '18 at 07:37
  • Use RxJava for synchronous calls https://stackoverflow.com/questions/35062485/rxjava-how-to-emit-observables-synchronously – Chetan Shelake Aug 24 '18 at 07:38

2 Answers2

15

I decided to use Dispatcher's setMaxRequests method to send request one at a time:

Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequests(1);

OkHttpClient client = new OkHttpClient.Builder()
                .dispatcher(dispatcher)
                .build()
Joe Rakhimov
  • 4,713
  • 9
  • 51
  • 109
0

yes you just need to call the function or send request on success/failure result of the API

  private void firstRequest() {


    Call<LoginModel> call= apiInterface.getLogin("");
    call.enqueue(new Callback<LoginModel>() {
        @Override
        public void onResponse(Call<LoginModel> call, Response<LoginModel> response) {
            //function here

        }

        @Override
        public void onFailure(Call<LoginModel> call, Throwable t) {

        }
    });


}
sourabh kaushik
  • 523
  • 4
  • 20
  • 1
    Thank you for your answer. In this way, I need to change everywhere in my code. I decided to use Dispatcher's setMaxRequests method as Arnab Kundu suggested. – Joe Rakhimov Aug 24 '18 at 07:21
  • 1
    Though it can work like this, a more general solution is using a dispatcher as Joe responded. – Adrian Coman Apr 23 '20 at 18:48