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 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.
Observable
s altogether? Then you could to something likeObservable.concat(simpleRequest, requestWithExtraHeader).take(1)
- which would only subscribe torequestWithExtraHeader
ifsimpleRequest
failed to produce an item... Something along that line? - david.mihola