Snippets

Victor ADASCALITEI Lifecycle aware Retrofit with uniform issue-routing

Created by Victor ADASCALITEI
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.IntDef;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Response;

public abstract class ObservedBackendOperation<T> {
    private MutableLiveData<T> mResponse;
    private MutableLiveData<Throwable> mReportedFailure;

    public ObservedBackendOperation() {
        this.mResponse = new MutableLiveData<>();
        this.mReportedFailure = new MutableLiveData<>();
    }

    public LiveData<T> whenDone() {
        return mResponse;
    }

    public LiveData<Throwable> whenReportingIssue() {
        return mReportedFailure;
    }

    public void go() {
        toDo(mResponse, mReportedFailure);
    }

    public abstract void toDo(MutableLiveData<T> resp,
                              MutableLiveData<Throwable> issue);

    /* package */ static class IssueResponse {
        @IntDef({IssueType.ALERT, IssueType.ERROR})
        public @interface IssueType {
            int ALERT = 1;
            int ERROR = 2;
        }

        @SerializedName("type") @IssueType private int mType;
        @SerializedName("reason") private String mReason;
    }

    @SuppressWarnings("PointlessBooleanExpression")
    public static class NotOkException extends Exception {
        private int mCode;
        private IssueResponse mIssue;

        /*package*/ NotOkException(int httpCode, IssueResponse resp) {
            this.mCode = httpCode;
            this.mIssue = resp;
        }

        public static NotOkException newFromResponse(Response resp) {
            NotOkException toRet = null;
            IssueResponse iResponse;

            if (resp != null && resp.isSuccessful() == false) {
                ResponseBody rawRespBody = (ResponseBody)resp.body();

                if (rawRespBody != null) {
                    try {
                        iResponse = new Gson().fromJson(rawRespBody.string(), IssueResponse.class);

                        toRet = new NotOkException(resp.code(), iResponse);
                    } catch (IOException ignored) {
                    }
                }
            } else {
                throw new IllegalArgumentException("Response is just fine. I can't extract a not-ok exception from it.");
            }

            return toRet;
        }
    }
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.