8

I am new to Retrofit Library. I am working on an app in which I've to make multiple API calls, but this problem sticks me when I tried to make my first API Call...

I am facing the issue that whenever I used to call retrofit's Asynchronous call method then the functionality inside onResponse method is running 2 times...

This is my code when I am calling the API call asynchronously...

final ApiModule apiService = ApiServiceGenerator.createService(ApiModule.class);
Call <ConfigResponse> call = apiService.getConfig();

call.enqueue(new Callback<ConfigResponse>() {
  @Override
  public void onResponse(Call<ConfigResponse> call, Response<ConfigResponse> response) {
    try {
        if (response.isSuccessful()) {
            Log.e("MyTag", "This is running");
        }
    } catch(Exception e) {
        e.printStackTrace();
    }
  }

  @Override
  public void onFailure(Call<ConfigResponse> call, Throwable t) {
    e.printStackTrace();
  }
});

As soon as I run the App on the device and when I see my android studio's logger, its is showing me the log message as -

E/MyTag: This is running
E/MyTag: This is running

It seems here that its running for 2 times..!!

I cannot understand that why is it running 2 times. Please help me out with this...

Just for more help... I've implemented my code like this.

ApiModule Interface (where I defined my API Call URLs)

public abstract interface ApiModule {

  @GET("config")
  Call<ConfigResponse> getConfig();

}

ApiServiceGenerator goes like this -

public class ApiServiceGenerator {

public static final String API_BASE_URL = "https://www.example.com/";
private static OkHttpClient httpClient = new OkHttpClient.Builder()
        .addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request newRequest = chain.request().newBuilder().addHeader("App-Secret", "some-secret-key").build();
                return chain.proceed(newRequest);
            }
        })
        .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) // Just For logging
        .readTimeout(60, TimeUnit.SECONDS)
        .connectTimeout(60, TimeUnit.SECONDS)
        .build();

Gson gson = new GsonBuilder()
        .registerTypeAdapterFactory(new ArrayAdapterFactory())
        .create();

private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .baseUrl(API_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create()));

public static <S> S createService(Class<S> serviceClass) {
    Retrofit retrofit = builder.client(httpClient).build();
    return retrofit.create(serviceClass);
}

public static Retrofit retrofit() { // For Error Handing when non-OK response is received from Server
    OkHttpClient httpClient = new OkHttpClient.Builder().build();
    OkHttpClient client = httpClient;
    return builder.client(client).build();
}
}
Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45
  • It is because, in your intercept implementation, the intercept method is again firing one more request using chain.request() – Thiyagu Jul 20 '22 at 05:06

3 Answers3

6

Finally I resolved my problem.. Its not the problem of the Retrofit library..!!

Actually its my bad. I am opening the fragment twice (which I don't know before answering this question)... That's why the code inside the fragment is running twice which makes me think as retrofit response is running twice...

Saumya Rastogi
  • 13,159
  • 5
  • 42
  • 45
  • 2
    there is another issue I ran into the exact problem but it happened that the enqueue call was being called 2 times directly. Still there are no other direct cause can be found. I am looking for another solution that can resolve this version 2.3.0 release. – Soma Hesk Feb 26 '18 at 08:07
  • @GFxJamal maybe you should check your interceptors to see if you are causing the call to be made more than once or your retrofit service builder configuration. – Manzur Alahi Oct 29 '19 at 16:41
6

In my case, I was using interceptors, inside one of them I called chain.proceed() twice. maybe you should check that too. this will not appear on your log. Use Stetho to check exactly how many times a call is being made.

Don't call any function from retrofit that returns "Response" more than once inside any of your interceptors.

Manzur Alahi
  • 1,870
  • 23
  • 19
1

In my case its called twice due to chain.proceed(request) called twice in same Interceptor

eg

class ErrorInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {

        val request: Request = chain.request()
        chain.proceed(request)
        val response = chain.proceed(request) // it called twice in this Interceptor
        when (response.code()) {
            

        }
        return response
    }
}
mani
  • 709
  • 6
  • 13