|
|
@@ -0,0 +1,83 @@
|
|
|
+package com.miekir.network.widget.observe.cancelable;
|
|
|
+
|
|
|
+import com.miekir.mvp.presenter.BasePresenter;
|
|
|
+import com.miekir.network.base.BaseResponse;
|
|
|
+import com.miekir.network.constant.Code;
|
|
|
+import com.miekir.network.utils.ExceptionUtil;
|
|
|
+
|
|
|
+import io.reactivex.internal.functions.Functions;
|
|
|
+import io.reactivex.internal.observers.LambdaObserver;
|
|
|
+
|
|
|
+/**
|
|
|
+ * Copyright (C), 2019-2020, Miekir
|
|
|
+ *
|
|
|
+ * @author Miekir
|
|
|
+ * @date 2020/11/21 17:25
|
|
|
+ * Description:
|
|
|
+ * 可手动取消的网络任务(可见可不见)
|
|
|
+ */
|
|
|
+public abstract class NetCancelableObserver<T> {
|
|
|
+ private CancelableConsumer<? super BaseResponse<T>> onNext;
|
|
|
+ private CancelableConsumer<? super Throwable> onError;
|
|
|
+
|
|
|
+ public NetCancelableObserver(final BasePresenter<?> presenter) {
|
|
|
+ this(presenter, false);
|
|
|
+ }
|
|
|
+
|
|
|
+ public NetCancelableObserver(final BasePresenter<?> presenter, final boolean withLoading) {
|
|
|
+ if (withLoading) {
|
|
|
+ presenter.showProgress();
|
|
|
+ }
|
|
|
+
|
|
|
+ onNext = new CancelableConsumer<BaseResponse<T>>() {
|
|
|
+ @Override
|
|
|
+ public void onResult(BaseResponse<T> response) {
|
|
|
+ if (withLoading) {
|
|
|
+ presenter.hideProgress();
|
|
|
+ }
|
|
|
+
|
|
|
+ try {
|
|
|
+ if (response.getCode() == Code.SUCCESS) {
|
|
|
+ onSuccess(response.getCode(), response.getContent());
|
|
|
+ } else if (response.getCode() == Code.TOKEN_TIMEOUT) {
|
|
|
+ // 重新登录
|
|
|
+ } else {
|
|
|
+ onFailure(response.getCode(), new Exception(response.getMessage()), response.getMessage());
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ onFailure(Code.FAILURE, new Exception("null"), null);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ };
|
|
|
+
|
|
|
+ onError = new CancelableConsumer<Throwable>() {
|
|
|
+ @Override
|
|
|
+ public void onResult(Throwable throwable) {
|
|
|
+ if (withLoading) {
|
|
|
+ presenter.hideProgress();
|
|
|
+ }
|
|
|
+ onFailure(Code.FAILURE, throwable, ExceptionUtil.exceptionHandler(throwable));
|
|
|
+ }
|
|
|
+ };
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 成功回调
|
|
|
+ * @param code 返回码
|
|
|
+ * @param t 返回的实体
|
|
|
+ */
|
|
|
+ public abstract void onSuccess(int code, T t);
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 失败回调
|
|
|
+ * @param code 返回码
|
|
|
+ * @param e 异常
|
|
|
+ * @param errMsg 异常信息
|
|
|
+ */
|
|
|
+ public abstract void onFailure(int code, Throwable e, String errMsg);
|
|
|
+
|
|
|
+ public LambdaObserver<BaseResponse<T>> getDisposal() {
|
|
|
+ return new LambdaObserver<BaseResponse<T>>(onNext, onError, Functions.EMPTY_ACTION, Functions.emptyConsumer());
|
|
|
+ }
|
|
|
+}
|