Kotlin coroutineScope 应该同时调用所有异步函数
我是 Kotlin 和 协程 的新手。
我有以下代码:
fun asyncCallForRelationIdList(relationIds: List<String>): List<Any?> = runBlocking {
println("Starting asynchronous code flow")
asyncCallForUserIdList(relationIds)
}
suspend fun asyncCallForUserIdList(userIds: List<String>): List<Any?> = coroutineScope {
println("Elements in list are supposed to call api concurrently")
val listval = mutableListOf<Any?>()
val result0 = async {restApiCall(relationId = userIds[0])}
val result1 = async {restApiCall(relationId = userIds[1])}
listval.add(result0.await())
listval.add(result1.await())
listval.toList()
}
suspend fun restApiCall(relationId: String): Any? {
println("api call... the api will timeout with an artificial delay")
//api call
//return "api result"
}
asyncCallForRelationIdList()
函数将调用 asyncCallForUserIdList()
,然后进行将超时的 API 调用。
我的问题是关于我在 coroutineScope 中使用的 async 关键字。我希望两个异步调用同时发生。但这里的情况并非如此。在第一个 api 调用之后,线程等待服务超时,而不是同时进行第二个 api 调用。为什么?
I am new to Kotlin and coroutines.
I have the below code:
fun asyncCallForRelationIdList(relationIds: List<String>): List<Any?> = runBlocking {
println("Starting asynchronous code flow")
asyncCallForUserIdList(relationIds)
}
suspend fun asyncCallForUserIdList(userIds: List<String>): List<Any?> = coroutineScope {
println("Elements in list are supposed to call api concurrently")
val listval = mutableListOf<Any?>()
val result0 = async {restApiCall(relationId = userIds[0])}
val result1 = async {restApiCall(relationId = userIds[1])}
listval.add(result0.await())
listval.add(result1.await())
listval.toList()
}
suspend fun restApiCall(relationId: String): Any? {
println("api call... the api will timeout with an artificial delay")
//api call
//return "api result"
}
asyncCallForRelationIdList()
function will call asyncCallForUserIdList()
which then makes an API call that will timeout.
My question is about the async
keyword that I am using in coroutineScope
. I expect the 2 async calls to happen concurrently. But that is not the case here. After the first api call, the thread waits for the service to timeout instead of making the 2nd api call concurrently. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在使用runBlocking,因此它会阻塞主线程并逐一运行。它不是启动异步代码流。
you are using runBlocking so its will block the main thread and run one by one. and its not Starting asynchronous code flow.
将异步调用更改为 async(Dispatchers.IO) { ... } 因为它们实际上不是异步的,目前它们在 runBlocking 的范围内运行
感谢@Pawel
Change your async calls to async(Dispatchers.IO) { ... } because they're not actually asynchronous, currently they're running in the scope of runBlocking
Thanks to @Pawel