问题遇到的现象和发生背景
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) {
}
})
}
}
两个方法换成异步返回,并且手动转换成的协程的返回。并输出耗时,依然是串行
我想要达到的结果
同时发起多个网络请求,耗时应该于最久耗时请求一致才对