Browse Source

- 网络请求取消销毁引用
- 无法显示空缺省页
- 优化异常信息显示

drake 5 years ago
parent
commit
ec7bd98457

+ 1 - 1
README.md

@@ -54,7 +54,7 @@ allprojects {
 module 的 build.gradle
 
 ```groovy
-implementation 'com.github.liangjingkanji:Net:1.1.9'
+implementation 'com.github.liangjingkanji:Net:1.2.0'
 ```
 
 

+ 1 - 1
net/build.gradle

@@ -40,7 +40,7 @@ dependencies {
     api 'com.yanzhenjie:okalle:0.1.7'
 
     compileOnly 'androidx.appcompat:appcompat:1.1.0'
-    compileOnly 'com.github.liangjingkanji:BRV:1.1.0'
+    compileOnly 'com.github.liangjingkanji:BRV:1.1.1'
 
     compileOnly 'io.reactivex.rxjava2:rxkotlin:2.3.0'
     compileOnly 'io.reactivex.rxjava2:rxandroid:2.1.1'

+ 8 - 5
net/src/main/java/com/drake/net/Net.kt

@@ -57,7 +57,8 @@ inline fun <reified M> get(
                 it.onError(e)
             }
         }
-    }.subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread())
+    }.onTerminateDetach().subscribeOn(Schedulers.computation())
+        .observeOn(AndroidSchedulers.mainThread())
 }
 
 
@@ -91,7 +92,7 @@ inline fun <reified M> syncGet(
                 it.onError(e)
             }
         }
-    }
+    }.onTerminateDetach()
 }
 
 
@@ -133,7 +134,8 @@ inline fun <reified M> post(
                 it.onError(e)
             }
         }
-    }.subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread())
+    }.onTerminateDetach().subscribeOn(Schedulers.computation())
+        .observeOn(AndroidSchedulers.mainThread())
 }
 
 
@@ -167,7 +169,7 @@ inline fun <reified M> syncPost(
                 it.onError(e)
             }
         }
-    }
+    }.onTerminateDetach()
 }
 
 
@@ -209,7 +211,8 @@ fun download(
                 it.onError(e)
             }
         }
-    }.subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread())
+    }.onTerminateDetach().subscribeOn(Schedulers.computation())
+        .observeOn(AndroidSchedulers.mainThread())
 }
 
 

+ 8 - 4
net/src/main/java/com/drake/net/NetConfig.kt

@@ -17,7 +17,9 @@ import android.os.Looper
 import android.widget.Toast
 import androidx.fragment.app.FragmentActivity
 import com.drake.brv.PageRefreshLayout
-import com.drake.net.error.*
+import com.drake.net.error.RequestParamsException
+import com.drake.net.error.ResponseException
+import com.drake.net.error.ServerResponseException
 import com.drake.net.observer.DialogObserver
 import com.drake.net.observer.PageObserver
 import com.yanzhenjie.kalle.Kalle
@@ -33,6 +35,7 @@ object NetConfig {
     internal var defaultToast: Toast? = null
     internal var onError: Throwable.() -> Unit = {
 
+
         val message = when (this) {
             is NetworkError -> app.getString(R.string.network_error)
             is URLError -> app.getString(R.string.url_error)
@@ -45,17 +48,18 @@ object NetConfig {
             is NoCacheError -> app.getString(R.string.no_cache_error)
             is ReadException -> app.getString(R.string.read_exception)
             is ParseError -> app.getString(R.string.parse_error)
-            is ParseJsonException -> app.getString(R.string.parse_json_error)
-            is JsonStructureException -> app.getString(R.string.json_structure_error)
             is RequestParamsException -> app.getString(R.string.request_error)
             is ServerResponseException -> app.getString(R.string.server_error)
             is ResponseException -> msg
             else -> {
-                printStackTrace()
                 app.getString(R.string.other_error)
             }
         }
 
+        if (BuildConfig.DEBUG) {
+            printStackTrace()
+        }
+
         app.toast(message)
     }
 }

+ 25 - 28
net/src/main/java/com/drake/net/convert/DefaultConverter.kt

@@ -9,26 +9,27 @@
 
 package com.drake.net.convert
 
-import com.drake.net.error.JsonStructureException
-import com.drake.net.error.ParseJsonException
 import com.drake.net.error.RequestParamsException
 import com.drake.net.error.ServerResponseException
 import com.yanzhenjie.kalle.Response
 import com.yanzhenjie.kalle.simple.Converter
 import com.yanzhenjie.kalle.simple.SimpleResponse
-import org.json.JSONException
 import org.json.JSONObject
 import java.lang.reflect.Type
 
 
 /**
- * 默认的转换器要求数据结构为JSON对象
+ * 默认的转换器实现, 如果不满足需求推荐参考后自定义实现
+ *
+ * @property success String 错误码表示请求成功的值
+ * @property code String 错误码的Key名称
+ * @property msg String 错误信息的Key名称
  */
 @Suppress("UNCHECKED_CAST")
 abstract class DefaultConverter(
-    val successCode: String = "0",
-    val codeName: String = "code",
-    val msgName: String = "msg"
+    val success: String = "0",
+    val code: String = "code",
+    val msg: String = "msg"
 ) : Converter {
 
 
@@ -47,32 +48,22 @@ abstract class DefaultConverter(
 
         when {
             code in 200..299 -> {
-                try {
-                    val jsonObject = JSONObject(body)
-                    val responseCode = jsonObject.optString(codeName)
+                val jsonObject = JSONObject(body)
+                val responseCode = jsonObject.getString(this.code)
 
-                    if (responseCode == successCode) {
-                        if (succeed === String::class.java) {
-                            succeedData = body as S
-                        } else {
-                            try {
-                                succeedData = convert(succeed, body)
-                            } catch (e: Exception) {
-                                e.printStackTrace()
-                                throw ParseJsonException(body)
-                            }
-                        }
+                if (responseCode == success) {
+                    succeedData = if (succeed === String::class.java) {
+                        body as S
                     } else {
-                        failedData = jsonObject.optString(msgName) as F
-                        code = responseCode.toInt()
+                        convert(succeed, body)
                     }
-                } catch (e: JSONException) {
-                    e.printStackTrace()
-                    throw JsonStructureException(body)
+                } else {
+                    failedData = jsonObject.getString(msg) as F
+                    code = responseCode.toInt()
                 }
             }
-            code in 400..499 -> throw RequestParamsException()
-            code >= 500 -> throw ServerResponseException()
+            code in 400..499 -> throw RequestParamsException(code)
+            code >= 500 -> throw ServerResponseException(code)
         }
 
         return SimpleResponse.newBuilder<S, F>().code(code)
@@ -84,5 +75,11 @@ abstract class DefaultConverter(
     }
 
 
+    /**
+     * 解析JSON数据
+     * @param succeed Type 请求函数传过来的字节码类型
+     * @param body String 一般为返回JSON
+     * @return S? 解析后的数据实体
+     */
     abstract fun <S> convert(succeed: Type, body: String): S?
 }

+ 0 - 16
net/src/main/java/com/drake/net/error/JsonStructureException.kt

@@ -1,16 +0,0 @@
-/*
- * Copyright (C) 2018, Umbrella CompanyLimited All rights reserved.
- * Project:Net
- * Author:Drake
- * Date:10/30/19 8:15 PM
- */
-
-package com.drake.net.error
-
-
-/**
- * JSON结构不符
- * 一般情况下属于code和msg无法获取
- */
-class JsonStructureException(val msg: String) : Throwable() {
-}

+ 0 - 11
net/src/main/java/com/drake/net/error/ParseJsonException.kt

@@ -1,11 +0,0 @@
-/*
- * Copyright (C) 2018, Umbrella CompanyLimited All rights reserved.
- * Project:Net
- * Author:Drake
- * Date:10/28/19 8:48 PM
- */
-
-package com.drake.net.error
-
-
-class ParseJsonException(val msg: String) : Throwable()

+ 1 - 1
net/src/main/java/com/drake/net/error/RequestParamsException.kt

@@ -10,4 +10,4 @@ package com.drake.net.error
 /**
  * 404
  */
-class RequestParamsException : Throwable()
+class RequestParamsException(code: Int) : Throwable(code.toString())

+ 1 - 1
net/src/main/java/com/drake/net/error/ServerResponseException.kt

@@ -10,4 +10,4 @@ package com.drake.net.error
 /**
  * 500
  */
-class ServerResponseException : Throwable()
+class ServerResponseException(code: Int) : Throwable(code.toString())

+ 1 - 1
net/src/main/java/com/drake/net/observer/DialogObserver.kt

@@ -76,7 +76,7 @@ abstract class DialogObserver<M>(
      */
     override fun onError(e: Throwable) {
         dismissDialog()
-        NetConfig.onError.invoke(e)
+        NetConfig.onError(e)
     }
 
     override fun onComplete() {

+ 1 - 1
net/src/main/java/com/drake/net/observer/NetObserver.kt

@@ -30,7 +30,7 @@ abstract class NetObserver<M>() : DefaultObserver<M>(), LifecycleObserver {
      * @param e 包括错误信息
      */
     override fun onError(e: Throwable) {
-        NetConfig.onError.invoke(e)
+        NetConfig.onError(e)
     }
 
     override fun onComplete() {

+ 16 - 18
net/src/main/java/com/drake/net/observer/PageObserver.kt

@@ -9,10 +9,14 @@ package com.drake.net.observer
 
 import android.view.View
 import android.view.View.OnAttachStateChangeListener
+import com.drake.brv.BindingAdapter
 import com.drake.brv.PageRefreshLayout
+import com.drake.net.BuildConfig
 import com.drake.net.NetConfig
 import com.drake.net.R
-import com.drake.net.error.*
+import com.drake.net.error.RequestParamsException
+import com.drake.net.error.ResponseException
+import com.drake.net.error.ServerResponseException
 import com.drake.net.toast
 import com.yanzhenjie.kalle.exception.*
 import io.reactivex.observers.DefaultObserver
@@ -32,30 +36,30 @@ abstract class PageObserver<M>(val pageRefreshLayout: PageRefreshLayout) : Defau
                 is URLError -> NetConfig.app.getString(R.string.url_error)
                 is HostError -> NetConfig.app.getString(R.string.host_error)
                 is ConnectTimeoutError -> NetConfig.app.getString(R.string.connect_timeout_error)
-                is ConnectException -> NetConfig.app.getString(R.string.connect_exception)
+                is ReadException -> NetConfig.app.getString(R.string.read_exception)
                 is WriteException -> NetConfig.app.getString(R.string.write_exception)
+                is ConnectException -> NetConfig.app.getString(R.string.connect_exception)
                 is ReadTimeoutError -> NetConfig.app.getString(R.string.read_timeout_error)
                 is DownloadError -> NetConfig.app.getString(R.string.download_error)
                 is NoCacheError -> NetConfig.app.getString(R.string.no_cache_error)
-                is ReadException -> NetConfig.app.getString(R.string.read_exception)
                 is ParseError -> NetConfig.app.getString(R.string.parse_error)
-                is ParseJsonException -> NetConfig.app.getString(R.string.parse_json_error)
-                is JsonStructureException -> NetConfig.app.getString(R.string.json_structure_error)
                 is RequestParamsException -> NetConfig.app.getString(R.string.request_error)
                 is ServerResponseException -> NetConfig.app.getString(R.string.server_error)
                 is ResponseException -> msg
                 else -> {
-                    printStackTrace()
                     NetConfig.app.getString(R.string.other_error)
                 }
             }
 
-            when (this) {
-                is ParseError, is ParseJsonException, is ResponseException, is RequestParamsException, is ServerResponseException -> NetConfig.app.toast(
-                    message
-                )
+            if (BuildConfig.DEBUG) {
+                printStackTrace()
             }
 
+            when (this) {
+                is ParseError, is ResponseException -> {
+                    NetConfig.app.toast(message)
+                }
+            }
         }
     }
 
@@ -77,17 +81,11 @@ abstract class PageObserver<M>(val pageRefreshLayout: PageRefreshLayout) : Defau
      * @param e 包括错误信息
      */
     override fun onError(e: Throwable) {
-        if (pageRefreshLayout.stateEnabled) {
-            pageRefreshLayout.showError()
-        } else pageRefreshLayout.finish(false)
-
+        pageRefreshLayout.showError()
         onPageError.invoke(e, pageRefreshLayout)
     }
 
     override fun onComplete() {
-        if (pageRefreshLayout.stateEnabled) {
-            pageRefreshLayout.showContent()
-        } else pageRefreshLayout.finish(true)
     }
 
     /**
@@ -95,7 +93,7 @@ abstract class PageObserver<M>(val pageRefreshLayout: PageRefreshLayout) : Defau
      *
      * @param data 要添加的数据集
      */
-    fun addData(data: List<Any>, hasMore: PageRefreshLayout.() -> Boolean) {
+    fun addData(data: List<Any>, hasMore: BindingAdapter.() -> Boolean) {
         pageRefreshLayout.addData(data, hasMore)
     }
 

+ 5 - 14
net/src/main/java/com/drake/net/observer/RefreshObserver.kt

@@ -18,37 +18,28 @@ import io.reactivex.observers.DefaultObserver
  */
 abstract class RefreshObserver<M>(
     val refreshLayout: SmartRefreshLayout,
-    val loadMore: Boolean = false
-) :
-    DefaultObserver<M>() {
+    val enableLoadMore: Boolean = false
+) : DefaultObserver<M>() {
 
 
     init {
+        refreshLayout.setEnableLoadMore(enableLoadMore)
         refreshLayout.addOnAttachStateChangeListener(object : OnAttachStateChangeListener {
             override fun onViewAttachedToWindow(v: View) {
 
             }
+
             override fun onViewDetachedFromWindow(v: View) {
                 cancel()
             }
         })
     }
 
-    override fun onStart() {
-        refreshLayout.setEnableLoadMore(loadMore)
-    }
-
-    /**
-     * 关闭进度对话框并提醒错误信息
-     *
-     * @param e 包括错误信息
-     */
     override fun onError(e: Throwable) {
         refreshLayout.finishRefresh(false)
-        NetConfig.onError.invoke(e)
+        NetConfig.onError(e)
     }
 
-
     override fun onComplete() {
         refreshLayout.finishRefresh(true)
     }

+ 1 - 3
net/src/main/res/values/strings.xml

@@ -8,14 +8,12 @@
     <string name="host_error">无法找到指定服务器主机</string>
     <string name="connect_timeout_error">连接服务器超时,请重试</string>
     <string name="connect_exception">请检查网络连接</string>
+    <string name="read_exception">读取数据错误</string>
     <string name="write_exception">发送数据错误</string>
     <string name="read_timeout_error">读取服务器数据超时,请检查网络</string>
     <string name="download_error">下载过程发生错误</string>
     <string name="no_cache_error">读取缓存错误</string>
     <string name="parse_error">解析数据时发生异常</string>
-    <string name="read_exception">读取数据错误</string>
-    <string name="parse_json_error">解析JSON错误</string>
-    <string name="json_structure_error">解析JSON错误</string>
     <string name="request_error">请求参数错误</string>
     <string name="server_error">服务响应错误</string>
     <string name="other_error">服务器未响应</string>

+ 3 - 1
sample/build.gradle

@@ -38,7 +38,9 @@ dependencies {
 
     implementation 'com.squareup.moshi:moshi-kotlin:1.8.0'
     kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.8.0'
-    implementation 'com.github.liangjingkanji:BRV:1.1.0'
+    implementation 'com.github.liangjingkanji:BRV:1.1.1'
+    implementation  'com.scwang.smart:refresh-header-classics:2.0.0-alpha-1'
+    implementation  'com.scwang.smart:refresh-footer-classics:2.0.0-alpha-1'
     implementation 'io.reactivex.rxjava2:rxkotlin:2.3.0'
     implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
 }

+ 8 - 0
sample/src/main/java/com/drake/net/sample/App.kt

@@ -3,6 +3,9 @@ package com.drake.net.sample
 import android.app.Application
 import com.drake.net.convert.DefaultConverter
 import com.drake.net.initNet
+import com.scwang.smart.refresh.footer.ClassicsFooter
+import com.scwang.smart.refresh.header.ClassicsHeader
+import com.scwang.smart.refresh.layout.SmartRefreshLayout
 import com.squareup.moshi.Moshi
 import java.lang.reflect.Type
 
@@ -18,5 +21,10 @@ class App : Application() {
                 }
             })
         }
+
+
+
+        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout -> ClassicsHeader(this) }
+        SmartRefreshLayout.setDefaultRefreshFooterCreator { context, layout -> ClassicsFooter(this) }
     }
 }

+ 0 - 7
sample/src/main/java/com/drake/net/sample/MainActivity.kt

@@ -2,8 +2,6 @@ package com.drake.net.sample
 
 import android.os.Bundle
 import androidx.appcompat.app.AppCompatActivity
-import com.drake.brv.utils.page
-import kotlinx.android.synthetic.main.activity_main.*
 
 class MainActivity : AppCompatActivity() {
 
@@ -11,10 +9,5 @@ class MainActivity : AppCompatActivity() {
         super.onCreate(savedInstanceState)
         setContentView(R.layout.activity_main)
 
-        content.page().onRefresh {
-
-        }
-
-
     }
 }

+ 3 - 4
sample/src/main/res/layout/activity_main.xml

@@ -1,9 +1,8 @@
 <?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-    xmlns:app="http://schemas.android.com/apk/res-auto"
+<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools"
-    android:layout_width="match_parent"
     android:id="@+id/content"
+    android:layout_width="match_parent"
     android:layout_height="match_parent"
     tools:context=".MainActivity">
 
@@ -12,4 +11,4 @@
         android:layout_height="wrap_content"
         android:text="Hello World!" />
 
-</LinearLayout>
+</FrameLayout>