Skip to content

Instantly share code, notes, and snippets.

@muratcanbur
Last active July 24, 2017 06:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muratcanbur/b175a54f8bc6c941ad210dc261c4db4a to your computer and use it in GitHub Desktop.
Save muratcanbur/b175a54f8bc6c941ad210dc261c4db4a to your computer and use it in GitHub Desktop.
DolapSubscriber is a base Rx Subscriber class that handles all API requests.
public abstract class DolapSubscriber<T> extends Subscriber<T> {
private MVPView mvpView;
public DolapSubscriber(MVPView mvpView) {
this.mvpView = mvpView;
}
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable throwable) {
if (throwable instanceof HttpException) {
callErrorHandler(((HttpException) throwable).response().errorBody());
} else if (throwable instanceof SocketTimeoutException) {
timeOutError();
} else if (throwable instanceof IOException) {
networkError();
}
}
private void timeOutError() {
if (mvpView != null) {
mvpView.dismissProgress();
mvpView.timeoutError();
}
}
private void callErrorHandler(ResponseBody message) {
try {
Gson gson = new Gson();
RestError restError = gson.fromJson(message.string(), RestError.class);
onError(restError);
} catch (Exception exception) {
Crashlytics.logException(exception);
onSystemError(getDefaultError());
}
}
private RestError getDefaultError() {
RestError restError = new RestError();
restError.setMessage("Lütfen tekrar deneyin. ");
return restError;
}
private void networkError() {
if (mvpView != null) {
mvpView.dismissProgress();
mvpView.networkError();
}
}
public void onError(RestError restError) {
onSystemError(restError);
}
private void onSystemError(RestError restError) {
if (mvpView != null) {
mvpView.dismissProgress();
mvpView.showError(restError);
}
}
@Override
public void onNext(T t) {
if (t instanceof Response) {
Response response = (Response) t;
if (!response.isSuccessful()) {
callErrorHandler(response.errorBody());
} else {
onSuccess(t);
}
} else {
onSuccess(t);
}
}
protected void onSuccess(T t) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment