In our app we met with one special case - if our App.specialFlag == true
, we need stop any request from our code. And we think, that the best approach in this situation is include special Interceptor
which will stop any our requests, something like this:
if (App.specialFlag) { // Somehow stop request } else { return chain.proceed(chain.request()); }
Also, we should note, that we use RxJavaCallAdapterFactory
for wrapping responses into Observable
s.
But we don't see any methods for stopping request in OkHttp Interceptors.
We came up with two ways to solve our issue:
a) Create special ApiService.class
for wrapping every request in our API like this:
public Observable<User> getUserDetails() { if (App.specialFlag) { return Observable.just(null); } return api.getUserDetails(); }
But we think that it is ugly and cumbersome solution.
b) Throw a RuntimeException
in Interceptor, then catch it in every place we use our API.
The second solution is also not good, because we need to include a lot of onErrorResumeNext
operators in our chains.
May be someone knows, how to handle our situation in more 'clever' way?..
Thanks in advance!
One thing missing in the accepted answer is that you need to specify the protocol and the message. If you don't specify that you will get an Exception. Looking like this:
if (App.specialFlag) { return new Response.Builder() .code(418) // Whatever code .body(ResponseBody.create(null, "")) // Whatever body .protocol(Protocol.HTTP_2) .message("Dummy response") .request(chain.request()) .build(); } else { return chain.proceed(chain.request()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With