Kotlin 协程(Coroutines)配合使用 Retrofit,网络请求

第一步 :添加所需依赖 

  //管理生命周期
    implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0"
    //添加支持Kotlin协程
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9"
    //添加Retrofit网络请求依赖
    implementation "com.jakewharton.retrofit:retrofit2-kotlin-coroutines-adapter:0.9.2"
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    //添加OKhttp相关依赖 可以用来配置其他配置属性
    implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.11.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
    implementation 'com.blankj:utilcode:1.28.1'

第二步 : 这里使用了 Kotlin的 DSL 语法创建了一个 数据返回回调监听

class RetrofitCoroutineDSL {

    internal var onSuccess : ((T) -> Unit)? = null
        private set
    internal var onFail: ((exception: RequestResultException) -> Unit)? = null
        private set
    internal var onComplete : (() -> Unit)? = null
        private set

    fun onSuccess(block : (T) -> Unit){
        this.onSuccess = block
    }

    fun onFail(block: (exception: RequestResultException) -> Unit) {
        this.onFail = block
    }

    fun onComplete(block : () -> Unit){
        this.onComplete = block
    }

    internal fun clean(){
        onSuccess = null
        onComplete = null
        onFail = null
    }
}

这里面包含了 自定义的异常处理(RequestResultException)

public class RequestResultException extends Exception{

    private static final int UNAUTHORIZED = 401;
    private static final int FORBIDDEN = 403;
    private static final int NOT_FOUND = 404;
    private static final int REQUEST_TIMEOUT = 408;
    private static final int INTERNAL_SERVER_ERROR = 500;
    private static final int BAD_GATEWAY = 502;
    private static final int SERVICE_UNAVAILABLE = 503;
    private static final int GATEWAY_TIMEOUT = 504;
    private static final int CONTENT_IS_TOO_LARGE = 413;

    private HttpResult result;
    private String errorMessage;
    private String errorType;
    private Throwable throwable;

    public RequestResultException(@NotNull Throwable throwable) {
        throwable.printStackTrace();
        this.throwable = throwable;
        if (throwable instanceof HttpException){
            switch (((HttpException) throwable).code()){
                case CONTENT_IS_TOO_LARGE:
                    errorMessage = "内容过大:"+((HttpException) throwable).code();
                    break;
                case UNAUTHORIZED:
                case FORBIDDEN:
                case NOT_FOUND:
                case REQUEST_TIMEOUT:
                case GATEWAY_TIMEOUT:
                case INTERNAL_SERVER_ERROR:
                case BAD_GATEWAY:
                case SERVICE_UNAVAILABLE:
                default:
                    errorMessage = "网络错误:"+((HttpException) throwable).code();
                    break;
            }
            try {
                ResponseBody responseBody = ((HttpException) throwable).response().errorBody();
                if (responseBody != null){
                    String errorMsg = new String(responseBody.bytes());
                    if (!TextUtils.isEmpty(errorMsg)){
                        result = GsonUtils.fromJson(errorMsg, HttpResult.class);
                        errorMessage = result.getMessage();
                        errorType = result.getMessageType();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if (throwable instanceof JsonParseException
                || throwable instanceof JSONException
                || throwable instanceof ParseException){
            errorMessage = "解析错误";
        }else if (throwable instanceof ConnectException) {
            errorMessage = "连接失败";
        }else if (throwable instanceof SocketTimeoutException){
            errorMessage = "连接超时";
        }else if (throwable instanceof SocketException){
            errorMessage = "连接关闭";
        }else if (throwable instanceof javax.net.ssl.SSLHandshakeException) {
            errorMessage = "证书验证失败";
        }else if (throwable instanceof ResponseMessageException) {
            result = ((ResponseMessageException) throwable).response();
            errorMessage = ((ResponseMessageException) throwable).errorMessage();
            errorType = ((ResponseMessageException) throwable).errorType();
        }else {
            try {
//                errorMessage = "未知错误:"+throwable.getMessage();
                errorMessage = "";
                /*Log.e("未知错误",throwable.getMessage());
                throwable.printStackTrace();*/
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public String getErrorType() {
        return errorType;
    }

    public HttpResult getResult() {
        return result;
    }

    public String getErrorCode(){
        return result != null ? (TextUtils.isEmpty(result.getErrorCode()) ? "" : result.getErrorCode()) : "";
    }

    public Throwable getThrowable() {
        return throwable;
    }
}

public final

你可能感兴趣的:(Android,Kotlin,android,Coroutines,kotlin,Retrofit)