灯塔@kuaidao 2022-04-11 18:32 采纳率: 50%
浏览 196
已结题

retrofit + kotlin 协程进行并发访问网络请求async { }.await(),通过输出log日志,发现是串行执行

问题遇到的现象和发生背景

retrofit + kotlin 协程进行并发访问网络请求,通过输出log日志,发现是串行执行

问题相关代码,请勿粘贴截图

1.Activity 内使用 MainScope().launch{ } 请求

     MainScope().launch {
            val time = measureTimeMillis {
                val time2 = measureTimeMillis {
                    val continueGames = async { getSynContinueGames(userCode) }.await()
                }
                Logger.d("耗时 getSynContinueGames=$time2")
                val time3 = measureTimeMillis {
                    val boutiqueGames = async { getSyncBoutiqueGames(gender) }.await()
                }
                Logger.d("耗时 getSyncBoutiqueGames=$time3")
                //PreloadingGames.setGames(boutiqueGames.await(), continueGames.await())
                Logger.d("总耗时 合计=(${time2.plus(time3)}")
            }
            Logger.d("总耗时 =$time")
            goToMain()
        }

网络请求


```kotlin
    suspend fun getSyncBoutiqueGames(gender: String): HomeBoutique? =
        withContext(Dispatchers.IO) {
            try {
                HttpManager.INSTANCE.request(HomeIService::class.java).getBoutiqueGames(gender)
                    .execute().let {
                        if (it.code() == 200 && null != it.body() && it.body()?.code == 1) it.body() else null
                    }
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
        }


    suspend fun getSynContinueGames(userCode: String): UcenterListBo? =
        withContext(Dispatchers.IO) {
            try {
                HttpManager.INSTANCE.request(HomeIService::class.java)
                    .getContinueGames(userCode, 1, 10).execute().let {
                        if (it.code() == 200 && null != it.body() && it.body()?.code == 1) it.body() else null
                    }
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
        }



###### 运行结果及报错内容 


```kotlin

SplashActivity.kt: ║     耗时 getSynContinueGames=229
SplashActivity.kt: ║     耗时 getSyncBoutiqueGames=378
SplashActivity.kt: ║     总耗时 合计=(607
SplashActivity.kt: ║     总耗时 =607

我的解答思路和尝试过的方法

第一眼看到是retrofit使用错了。使用的是同步请求。后面从网上搜索到一个写法

   suspend fun getSyncBoutiqueGames(gender: String): HomeBoutique? =

        withContext(Dispatchers.IO) {
            suspendCancellableCoroutine { cancellableContinuation ->
                HttpManager.INSTANCE.request(HomeIService::class.java).getBoutiqueGames(gender)
                    .enqueue(
                        object : Callback<HomeBoutique> {
                            override fun onResponse(
                                call: Call<HomeBoutique>,
                                response: Response<HomeBoutique>
                            ) {
                                val body = response.body()
                                body?.let {
                                    cancellableContinuation.resumeWith(Result.success(body))
                                }
                            }

                            override fun onFailure(call: Call<HomeBoutique>, t: Throwable) {

                            }

                        })

            }

        }

两个方法换成异步返回,并且手动转换成的协程的返回。并输出耗时,依然是串行

我想要达到的结果

同时发起多个网络请求,耗时应该于最久耗时请求一致才对

  • 写回答

1条回答 默认 最新

  • 灯塔@kuaidao 2022-04-11 19:23
    关注

    写错了

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 4月19日
  • 已采纳回答 4月11日
  • 创建了问题 4月11日

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛