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 way to prevent request from being executed(before it starts) it to simply do as you tried to, but with an addition of Response.Builder:
if (App.specialFlag) {
return new Response.Builder()
.code(600) //Simply put whatever value you want to designate to aborted request.
.protocol(Protocol.HTTP_2)
.message("Dummy response")
.request(chain.request())
.build();
} else {
return chain.proceed(chain.request());
}
EDIT 26/09/2019 Updated answer with details mentioned by Bobstring