0
votes

I have rxjava(observable) + retrofit2 together to make http requests to my application. I create OkHttpClient once for app and don't want to recreate it. I have retry logic implemented on observable level - using filter, retryWhen together. What I want - if request finished with error from server side, i want to retry it and send additional header with it. So, I dont understand neither how can I modify observable inside retryWhen nor how to get the knowledge about observable from interceptor level. Any ideas and/or knowledge about possible approaches?

1
I don't think what you're proposing can work. For one thing the okhttpclient and Retrofit instances are immutable. This means you can't add and remove interceptors from the client once it has been built. You also can't change the client used by the retrofit instance once it has been set. - JohnWowUs
you could write an interceptor which will execute the same request with a new header in case of server failure. Would that work for you? - LordRaydenMK
Would it make sense to think of the different versions of the request just as different Observables altogether? Then you could to something like Observable.concat(simpleRequest, requestWithExtraHeader).take(1) - which would only subscribe to requestWithExtraHeader if simpleRequest failed to produce an item... Something along that line? - david.mihola
Can you provide example (Retrofit interface and Observable logic)? - Aleksander Mielczarek

1 Answers

0
votes

You need to create your own Interceptor implementation where you can setup the header logic. Something like

public class FallbackInterceptor implements Interceptor {
  static String header1Key = "key1";
  static String extraHeaderKey = "key2";
  String header1, extraHeader;
  boolean useextraheader = false;

  public FallbackInterceptor(string header1, string extraheader) {
    this.header1 = header1;
    this.extraheader = extraheader;

  }

  public void setUseExtraHeader(boolean useextraheader) {
    this.userextraheader = useextraheader;
  }

  @Override 
  public Response intercept(Interceptor.Chain chain) throws IOException {
    Request original = chain.request();
    // Add request headers
    Request.Builder requestBuilder = original.newBuilder().header(header1Key, header1);
    if (useExtraHeader) {
        requestBuilder = requestBuilder.header(extraHeaderKey, extraHeader)
    }
    Request newRequest = requestBuilder.method(original.method(), original.body())
                                       .build();
    // Return the response
    return chain.proceed(request);
  }
}

Add this to an okhttpclient and have your retrofit instance use this this. You can then manipulate the extraheader flag in your retry logic.