Kotlin在Android开发中合并异步任务的思考

直接上代码示例吧 ,其实思路很简单

launch(Main) {
    
    
      val startTime = System.currentTimeMillis()
      val a = async {
    
    
          delay(4000)
          1
      }
      val b = async {
    
    
          delay(5000)
          "Kotlin在Android开发中合并异步任务的思考"
      }
       val c = suspendingMerge(a, b,errorBlock = {
    
    it.printStackTrace()})
      Log.e(
          "suspendingMerge",
          "time = ${
      
      (System.currentTimeMillis() - startTime) / 1000 % 60} ,data = $c"
      )
  }

关键方法

 suspend fun suspendingMerge(vararg params: Deferred<Any>,errorBlock:suspend CoroutineScope.(Exception) -> Unit): MutableList<Any> {
    
    
        val list = mutableListOf<Any>()
        try {
    
    
            list.addAll(mutableListOf(params.map {
    
     it.await() }))
        }catch (e:Exception){
    
    
            errorBlock(e)
        }
        return list
    }

可能有的同学会问最新版本的retrofit本身就已经支持kotlin的协程了,会直接返回自己想要的值,那你使用
async把请求包起来就可以了

猜你喜欢

转载自blog.csdn.net/wwq614003946wwq/article/details/100662254