importandroid.arch.lifecycle.LiveData;importandroid.arch.lifecycle.MutableLiveData;importandroid.support.annotation.IntDef;importcom.google.gson.Gson;importcom.google.gson.annotations.SerializedName;importjava.io.IOException;importokhttp3.ResponseBody;importretrofit2.Response;publicabstractclassObservedBackendOperation<T>{privateMutableLiveData<T>mResponse;privateMutableLiveData<Throwable>mReportedFailure;publicObservedBackendOperation(){this.mResponse=newMutableLiveData<>();this.mReportedFailure=newMutableLiveData<>();}publicLiveData<T>whenDone(){returnmResponse;}publicLiveData<Throwable>whenReportingIssue(){returnmReportedFailure;}publicvoidgo(){toDo(mResponse,mReportedFailure);}publicabstractvoidtoDo(MutableLiveData<T>resp,MutableLiveData<Throwable>issue);/* package */staticclassIssueResponse{@IntDef({IssueType.ALERT,IssueType.ERROR})public@interfaceIssueType{intALERT=1;intERROR=2;}@SerializedName("type")@IssueTypeprivateintmType;@SerializedName("reason")privateStringmReason;}@SuppressWarnings("PointlessBooleanExpression")publicstaticclassNotOkExceptionextendsException{privateintmCode;privateIssueResponsemIssue;/*package*/NotOkException(inthttpCode,IssueResponseresp){this.mCode=httpCode;this.mIssue=resp;}publicstaticNotOkExceptionnewFromResponse(Responseresp){NotOkExceptiontoRet=null;IssueResponseiResponse;if(resp!=null&&resp.isSuccessful()==false){ResponseBodyrawRespBody=(ResponseBody)resp.body();if(rawRespBody!=null){try{iResponse=newGson().fromJson(rawRespBody.string(),IssueResponse.class);toRet=newNotOkException(resp.code(),iResponse);}catch(IOExceptionignored){}}}else{thrownewIllegalArgumentException("Response is just fine. I can't extract a not-ok exception from it.");}returntoRet;}}}
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.