Created
April 20, 2017 15:19
-
-
Save 4gus71n/65dc94de4ca01fb221a079b68c0570b5 to your computer and use it in GitHub Desktop.
ServerSubscriber
This file contains 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
package com.siplay.android_siplay.helper; | |
import android.support.annotation.CallSuper; | |
import retrofit2.Response; | |
/** | |
* Created by Agustin Tomas Larghi on 20/04/2017. | |
* Email: agustin.tomas.larghi@gmail.com | |
*/ | |
public abstract class ServerSubscriber<APIDATA> extends rx.Subscriber<Response<APIDATA>> { | |
@Override @CallSuper | |
public void onCompleted() { | |
//Optional to implement | |
} | |
@Override @CallSuper | |
public void onError(Throwable e) { | |
//Optional to implement | |
onServerSideError(e); | |
} | |
@Override @CallSuper | |
public void onNext(Response<APIDATA> o) { | |
//Optional to implement | |
if (o.code() != 200) { | |
if (o.code() == 304) { | |
onSuccess(o.body()); | |
onNotModified(o.body()); | |
} else { | |
onServerSideError(new ServerSideErrorException(o)); | |
} | |
} else { | |
onServerSideResponse(o.body()); | |
onSuccess(o.body()); | |
} | |
} | |
/** | |
* Hook from this method if you wanna handle specific server-side responses (non-304) | |
* @param responseBody | |
*/ | |
protected void onServerSideResponse(APIDATA responseBody) { | |
//Optional to implement | |
} | |
/** | |
* You must implement this methods. Handles if something goes wrong. | |
* @param errorResponse | |
*/ | |
protected abstract void onServerSideError(Throwable errorResponse); | |
/** | |
* Hook from this method if you wanna handle specific not-modified respones (non-202) | |
* @param responseBody | |
*/ | |
protected void onNotModified(APIDATA responseBody) { | |
//Optional to implement | |
} | |
/** | |
* You must implement this method, is executed if everything went OK while doing the request. Is | |
* executed right after {@link #onServerSideResponse(Object)} and {@link #onNotModified(Object)} | |
* @param responseBody | |
*/ | |
protected abstract void onSuccess(APIDATA responseBody); | |
private class ServerSideErrorException extends RuntimeException { | |
public final Response<APIDATA> mErrorReq; | |
public ServerSideErrorException(Response<APIDATA> errorRequest) { | |
super(); | |
mErrorReq = errorRequest; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment