Browse Source

* 修复同步请求时默认吐司崩溃

drake 5 years ago
parent
commit
baa85d1c86

+ 5 - 3
README.md

@@ -38,7 +38,7 @@
 
 ## 安装
 
-project of build.gradle
+project  build.gradle
 
 ```groovy
 allprojects {
@@ -51,16 +51,18 @@ allprojects {
 
 
 
-module of build.gradle
+module  build.gradle
 
 ```groovy
-implementation 'com.github.liangjingkanji:Net:1.1.7'
+implementation 'com.github.liangjingkanji:Net:1.1.9'
 ```
 
 
 
 
 
+
+
 ## 初始化和配置
 
 ```kotlin

+ 0 - 1
net/build.gradle

@@ -44,5 +44,4 @@ dependencies {
 
     compileOnly 'io.reactivex.rxjava2:rxkotlin:2.3.0'
     compileOnly 'io.reactivex.rxjava2:rxandroid:2.1.1'
-
 }

+ 24 - 1
net/src/main/java/com/drake/net/NetConfig.kt

@@ -11,6 +11,9 @@ package com.drake.net
 
 import android.app.Application
 import android.app.Dialog
+import android.content.Context
+import android.os.Handler
+import android.os.Looper
 import android.widget.Toast
 import androidx.fragment.app.FragmentActivity
 import com.drake.brv.PageRefreshLayout
@@ -27,6 +30,7 @@ object NetConfig {
     lateinit var host: String
     lateinit var app: Application
 
+    internal var defaultToast: Toast? = null
     internal var onError: Throwable.() -> Unit = {
 
         val message = when (this) {
@@ -52,7 +56,26 @@ object NetConfig {
             }
         }
 
-        Toast.makeText(app, message, Toast.LENGTH_SHORT).show()
+        app.toast(message)
+    }
+}
+
+
+internal fun Context.toast(message: CharSequence, config: Toast.() -> Unit = {}) {
+    NetConfig.defaultToast?.cancel()
+
+    runMain {
+        NetConfig.defaultToast =
+            Toast.makeText(this, message, Toast.LENGTH_SHORT).apply { config() }
+        NetConfig.defaultToast?.show()
+    }
+}
+
+private fun runMain(block: () -> Unit) {
+    if (Looper.myLooper() == Looper.getMainLooper()) {
+        block()
+    } else {
+        Handler(Looper.getMainLooper()).post { block() }
     }
 }
 

+ 4 - 3
net/src/main/java/com/drake/net/observer/PageObserver.kt

@@ -9,11 +9,11 @@ package com.drake.net.observer
 
 import android.view.View
 import android.view.View.OnAttachStateChangeListener
-import android.widget.Toast
 import com.drake.brv.PageRefreshLayout
 import com.drake.net.NetConfig
 import com.drake.net.R
 import com.drake.net.error.*
+import com.drake.net.toast
 import com.yanzhenjie.kalle.exception.*
 import io.reactivex.observers.DefaultObserver
 
@@ -51,8 +51,9 @@ abstract class PageObserver<M>(val pageRefreshLayout: PageRefreshLayout) : Defau
             }
 
             when (this) {
-                is ParseError, is ParseJsonException, is ResponseException, is RequestParamsException, is ServerResponseException ->
-                    Toast.makeText(NetConfig.app, message, Toast.LENGTH_SHORT).show()
+                is ParseError, is ParseJsonException, is ResponseException, is RequestParamsException, is ServerResponseException -> NetConfig.app.toast(
+                    message
+                )
             }
 
         }