Reputation: 123
How to check a network connection and is the server available for all requests, using retrofit2 and rxjava2?
I can check the “server available” by sending a request to my server url, but can I check the network connection by sending a request to google.com or to another “good” website?
I have more api requests, for example one of this:
compositeDisposable.add(RetrofitClient
.getApi()
.somemethod()
.map(response -> {
Data data = null;
if (response.isSuccessful()) {
data = response.body();
} else {
data = new Data();
data.setResponseCode(response.code())
}
return data;
})
.onErrorReturnItem(new Data())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::checkResponse());
How to check these errors, which I wrote, for all requests in order not to duplicate the code? Thanks.
Upvotes: 0
Views: 858
Reputation: 10815
You could use lift
method which allow you to implement your own operator for your case ApiErrorOperator
And use it as follow :
@Override
public @NonNull Observable<List<Category>> fetchCategories() {
return this.service
.categories()
.lift(apiErrorOperator())
.map(CategoriesEnvelope::categories)
.subscribeOn(Schedulers.io());
}
Upvotes: 0
Reputation: 10330
Call RxJavaPlugins.setErrorHandler
in onCreate
of your application class. For example:
RxJavaPlugins.setErrorHandler(e -> {
if ((e instanceof IOException) || (e instanceof SocketException)) {
// handle exception
return;
}
});
Upvotes: 1