Selaa lähdekoodia

+ 轮循器增加倒计时功能
| 修复对话框取消网络请求没有自动取消问题

drake 4 vuotta sitten
vanhempi
commit
8f563f8aa1

+ 17 - 16
README.md

@@ -1,12 +1,12 @@
 # Net
 
-异步任务库, Android 创新式的网络请求库(针对[Kalle](https://github.com/yanzhenjie/Kalle)网络请求框架进行扩展), 支持协程高并发网络请求
+Android上 最强网络任务库, 创新式的网络请求库(针对[Kalle](https://github.com/yanzhenjie/Kalle)网络请求框架进行扩展), 支持协程高并发网络请求
 
 
 
-本项目为Android项目中的所有的异步任务和网络请求而生
+本项目为Android项目中的所有的异步任务和网络请求而生, Demo示例代码不过百行, 欢迎阅读
 
-The project is supported by [JetBrains](https://www.jetbrains.com/), Best IDE to developer <img src="https://tva1.sinaimg.cn/large/006tNbRwgy1gaskr305czj30u00wjtcz.jpg" alt="jetbrains" style="zoom:8%;" />
+The project is supported by [JetBrains](https://www.jetbrains.com/), Best IDE to developer <img src="https://tva1.sinaimg.cn/large/006tNbRwgy1gaskr305czj30u00wjtcz.jpg" alt="jetbrains" style="zoom:5%;" />
 
 
 
@@ -81,9 +81,9 @@ implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.0'
 implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.0'
 
 // 支持自动下拉刷新和缺省页的, 可选, 刷新头和上拉加载参考SmartRefreshLayout (可选)
-implementation 'com.github.liangjingkanji:BRV:1.3.3'
+implementation 'com.github.liangjingkanji:BRV:1.3.4'
 
-implementation 'com.github.liangjingkanji:Net:2.2.1'
+implementation 'com.github.liangjingkanji:Net:2.2.2'
 ```
 
 
@@ -94,7 +94,7 @@ implementation 'com.github.liangjingkanji:Net:2.2.1'
 
 请求方式支持同步和异步, 异步只允许在作用域内执行. 详情请看`Net.kt`文件
 
-![image-20191223150901891](https://tva1.sinaimg.cn/large/006tNbRwgy1ga6o9s47lsj30dg0ca0tz.jpg)
+![image-20200626032128956](https://i.imgur.com/gjWnbLx.png)
 
 
 
@@ -106,7 +106,7 @@ implementation 'com.github.liangjingkanji:Net:2.2.1'
 
 ```kotlin
 scopeNetLife {
-  val data = post<String>("https://raw.githubusercontent.com/liangjingkanji/BRV/master/README.md")
+  val data = Post<String>("https://raw.githubusercontent.com/liangjingkanji/BRV/master/README.md")
   textView.text = data.await()
 }
 ```
@@ -120,7 +120,7 @@ scopeNetLife {
 ```kotlin
 scopeNetLife {
 
-  val data = get<String>(
+  val data = Get<String>(
     "https://raw.githubusercontent.com/liangjingkanji/BRV/master/README.md",
     absolutePath = true
   )
@@ -138,7 +138,7 @@ scopeNetLife {
 ```kotlin
 scopeNetLife {
 
-  val data = post<String>(
+  val data = Post<String>(
     "https://raw.githubusercontent.com/liangjingkanji/BRV/master/README.md",
     absolutePath = true
   ){
@@ -157,7 +157,7 @@ scopeNetLife {
 
 ```kotlin
 scopeNetLife {
-  download("/path", "下载目录"){
+  Download("/path", "下载目录"){
 
     // 进度监听
     onProgress { progress, byteCount, speed ->
@@ -175,7 +175,7 @@ scopeNetLife {
 下载图片要求首先导入Glide依赖库, 下载图片和下载文件不同在于可以手动指定图片宽高
 
 ```kotlin
-Context.downloadImg(url: String, with: Int = -1, height: Int = -1)
+Context.DownloadImage(url: String, with: Int = -1, height: Int = -1)
 ```
 
 
@@ -185,7 +185,7 @@ Context.downloadImg(url: String, with: Int = -1, height: Int = -1)
 ```kotlin
 scopeNetLife {
 
-  val data = downImage(
+  val data = DownloadImage(
     "https://cdn.sspai.com/article/ebe361e4-c891-3afd-8680-e4bad609723e.jpg?imageMogr2/quality/95/thumbnail/!2880x620r/gravity/Center/crop/2880x620/interlace/1".
     200,200
   ).await()
@@ -482,7 +482,7 @@ pageRefreshLayout.onRefresh {
 
   pageRefreshLayout.scope {
 
-    val result = post<Model>("/path"){
+    val result = Post<Model>("/path"){
       param("key", "value")
       param("page", index) // 页面索引使用pageRefreshLayout的属性index
     }
@@ -538,7 +538,7 @@ Tip: PageRefreshLayout只要加载成功后即使后续请求失败也不会显
 ```kotlin
 scopeDialog {
 
-  val data = get<String>(
+  val data = Get<String>(
     "https://raw.githubusercontent.com/liangjingkanji/BRV/master/README.md",
     absolutePath = true
   )
@@ -660,7 +660,7 @@ scopeNetLife {
 
   Log.d("日志", "网络请求")
 
-  val data = get<String>(
+  val data = Get<String>(
     "https://raw.githubusercontent.com/liangjingkanji/BRV/master/README.md",
     cache = CacheMode.NETWORK_YES_THEN_WRITE_CACHE,
     absolutePath = true
@@ -672,7 +672,7 @@ scopeNetLife {
 
   Log.d("日志", "读取缓存")
 
-  val data = get<String>(
+  val data = Get<String>(
     "https://raw.githubusercontent.com/liangjingkanji/BRV/master/README.md",
     cache = CacheMode.READ_CACHE,
     absolutePath = true
@@ -739,4 +739,5 @@ reset // 重置轮循器 (包含计数器count和计时period) 不会停止轮
 switch //  切换轮循器开关
 
 state // 得到当前轮循器的状态
+life() // 绑定生命周期, 自动取消轮循器
 ```

+ 1 - 1
net/src/main/java/com/drake/net/scope/DialogCoroutineScope.kt

@@ -50,7 +50,7 @@ class DialogCoroutineScope(
                 progress
             }
         }
-        dialog?.setOnDismissListener { }
+        dialog?.setOnDismissListener { cancel() }
         dialog?.setCancelable(cancelable)
         dialog?.show()
     }

+ 19 - 23
net/src/main/java/com/drake/net/time/Interval.kt

@@ -15,7 +15,6 @@ import androidx.lifecycle.LifecycleOwner
 import com.drake.net.scope.AndroidScope
 import com.drake.net.utils.scope
 import kotlinx.coroutines.ObsoleteCoroutinesApi
-import kotlinx.coroutines.cancel
 import kotlinx.coroutines.channels.ReceiveChannel
 import kotlinx.coroutines.channels.TickerMode
 import kotlinx.coroutines.channels.ticker
@@ -42,21 +41,17 @@ import java.util.concurrent.TimeUnit
  * @param period 事件间隔
  * @param unit 事件单位
  * @param initialDelay 第一次事件的间隔时间
- * @param start 开始值
+ * @param start 开始值, 当[start]]比[end]值大, 且end不等于-1时, 即为倒计时
  */
-class Interval(
-    var end: Long, // -1 表示永远不结束, 可以修改
-    private val period: Long,
-    private val unit: TimeUnit,
-    private val initialDelay: Long = period,
-    private val start: Long = 0
-) : Serializable {
-
-    constructor(
-        period: Long,
-        unit: TimeUnit,
-        initialDelay: Long = period
-    ) : this(-1, period, unit, initialDelay, 0)
+class Interval(var end: Long, /* -1 表示永远不结束, 可以修改*/
+               private val period: Long,
+               private val unit: TimeUnit,
+               private val start: Long = 0,
+               private val initialDelay: Long = period) : Serializable {
+
+    constructor(period: Long,
+                unit: TimeUnit,
+                initialDelay: Long = period) : this(-1, period, unit, 0, initialDelay)
 
     private val receiveList: MutableList<(Long) -> Unit> = mutableListOf()
     private val finishList: MutableList<(Long) -> Unit> = mutableListOf()
@@ -157,14 +152,15 @@ class Interval(
         if (state == IntervalStatus.STATE_ACTIVE) launch()
     }
 
+    // </editor-fold>
+
+    //<editor-fold desc="生命周期">
     /**
-     * 生命周期
+     * 绑定生命周期, 在指定生命周期发生时取消轮循器
      * @param lifecycleOwner 默认在销毁时取消轮循器
      */
-    fun life(
-        lifecycleOwner: LifecycleOwner,
-        lifeEvent: Lifecycle.Event = Lifecycle.Event.ON_DESTROY
-    ): Interval {
+    fun life(lifecycleOwner: LifecycleOwner,
+             lifeEvent: Lifecycle.Event = Lifecycle.Event.ON_STOP): Interval {
         lifecycleOwner.lifecycle.addObserver(object : LifecycleEventObserver {
             override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                 if (lifeEvent == event) scope?.cancel()
@@ -172,8 +168,7 @@ class Interval(
         })
         return this
     }
-
-    // </editor-fold>
+    //</editor-fold>
 
     private fun launch(delay: Long = unit.toMillis(initialDelay)) {
         scope = scope {
@@ -182,7 +177,8 @@ class Interval(
 
             for (unit in ticker) {
 
-                count++
+                if (end != -1L && start > end) count-- else count++
+
                 countTime = System.currentTimeMillis()
 
                 receiveList.forEach {

+ 1 - 0
sample/build.gradle

@@ -65,6 +65,7 @@ dependencies {
     implementation 'com.github.liangjingkanji:StatusBar:1.0.3' // 透明状态栏
     implementation "com.github.liangjingkanji:LogCat:1.0" // 日志输出工具
     implementation 'com.github.liangjingkanji:debugkit:1.2.9'
+    implementation 'com.github.liangjingkanji:Tooltip:1.0.4'
 
     // ------------------------------Google数据库-------------------------------------
     implementation "androidx.room:room-runtime:$room_version"

+ 7 - 0
sample/src/main/java/com/drake/net/sample/ui/fragment/ConfigDialogFragment.kt

@@ -15,7 +15,9 @@ import androidx.fragment.app.Fragment
 import com.drake.net.Post
 import com.drake.net.sample.R
 import com.drake.net.utils.scopeDialog
+import com.drake.tooltip.toast
 import kotlinx.android.synthetic.main.fragment_config_dialog.*
+import kotlinx.coroutines.CancellationException
 
 
 class ConfigDialogFragment : Fragment() {
@@ -36,6 +38,11 @@ class ConfigDialogFragment : Fragment() {
                 param("u_name", "drake")
                 param("pwd", "123456")
             }.await()
+        }.finally {
+            // 关闭对话框后执行的异常
+            if (it is CancellationException) {
+                toast("对话框被关闭, 网络请求自动取消") // 这里存在Handler吐司崩溃, 如果不想处理就直接使用我的吐司库 https://github.com/liangjingkanji/Tooltip
+            }
         }
     }
 }

+ 5 - 5
sample/src/main/java/com/drake/net/sample/ui/fragment/SuperIntervalFragment.kt

@@ -24,9 +24,9 @@ class SuperIntervalFragment : Fragment() {
     lateinit var interval: Interval
 
     override fun onCreateView(
-        inflater: LayoutInflater, container: ViewGroup?,
-        savedInstanceState: Bundle?
-    ): View? {
+            inflater: LayoutInflater, container: ViewGroup?,
+            savedInstanceState: Bundle?
+                             ): View? {
 
         return inflater.inflate(R.layout.fragment_super_interval, container, false)
     }
@@ -36,8 +36,8 @@ class SuperIntervalFragment : Fragment() {
 
         initToolbar()
 
-        interval = Interval(1, TimeUnit.SECONDS, 0) // 每秒回调一次, 不会自动结束
-        // interval = Interval(10, 1, TimeUnit.SECONDS, 0, 0) // 自定义计数器个数的轮循器
+        interval = Interval(1, 1, TimeUnit.SECONDS, 5).life(this) // 自定义计数器个数的轮循器, 当[start]]比[end]值大, 且end不等于-1时, 即为倒计时
+        // interval = Interval(0, 1, TimeUnit.SECONDS) // 每秒回调一次, 不会自动结束
 
         interval.subscribe {
             tv_fragment.text = it.toString()

+ 1 - 1
sample/src/main/res/navigation/nav_main.xml

@@ -9,7 +9,7 @@
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:id="@+id/main"
-    app:startDestination="@id/download_img">
+    app:startDestination="@id/super_interval">
 
     <fragment
         android:id="@+id/async_task"