Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we have any possibility to stop request in OkHttp Interceptor?

Tags:

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 Observables.

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!

like image 509
Pavel Strelchenko Avatar asked May 31 '16 08:05

Pavel Strelchenko


1 Answers

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()); } 
like image 169
Bobstring Avatar answered Sep 21 '22 03:09

Bobstring