Last active
July 24, 2017 06:42
-
-
Save muratcanbur/b175a54f8bc6c941ad210dc261c4db4a to your computer and use it in GitHub Desktop.
DolapSubscriber is a base Rx Subscriber class that handles all API requests.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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