Kotlin协程,如何异步调用列表并将结果作为映射返回

Kotlin协程,如何异步调用列表并将结果作为映射返回,kotlin,kotlin-coroutines,Kotlin,Kotlin Coroutines,所以我希望所有service.charge函数都在单独的线程中运行。完成所有操作后返回地图希望解决您的问题: 假设您的服务和请求如下: 接口服务{ 暂停乐趣chargeForType1:ChargeResponse 暂停乐趣chargeForType2:ChargeResponse } 数据类Requestval vendorType:vendorType suspend fun requestAllrequests:列表:映射{ 回程视野{ 请求 .map{请求-> 异步的{ request.

所以我希望所有service.charge函数都在单独的线程中运行。完成所有操作后返回地图

希望解决您的问题:

假设您的服务和请求如下:

接口服务{ 暂停乐趣chargeForType1:ChargeResponse 暂停乐趣chargeForType2:ChargeResponse } 数据类Requestval vendorType:vendorType suspend fun requestAllrequests:列表:映射{ 回程视野{ 请求 .map{请求-> 异步的{ request.vendorType到when request.vendorType{ VendorType.Type1->service.chargeForType1 VendorType.Type2->service.chargeForType2 else->throw NotImplementedError${request.vendorType}尚不支持 } } } .等等 汤玛普先生 } }
希望解决您的问题:

假设您的服务和请求如下:

接口服务{ 暂停乐趣chargeForType1:ChargeResponse 暂停乐趣chargeForType2:ChargeResponse } 数据类Requestval vendorType:vendorType suspend fun requestAllrequests:列表:映射{ 回程视野{ 请求 .map{请求-> 异步的{ request.vendorType到when request.vendorType{ VendorType.Type1->service.chargeForType1 VendorType.Type2->service.chargeForType2 else->throw NotImplementedError${request.vendorType}尚不支持 } } } .等等 汤玛普先生 } }
service.charge是一个很长的计算过程,还是从网络上获取一些东西?它会呼叫其他服务向用户收费。通常2-3秒,这样的函数要么是Kotlin挂起函数,要么接受回调。是否有您正在使用的库?使用@Async和completableFuture。但是仍然不知道在这种情况下如何使用CompletableFuture。您使用的是Java库还是为什么有一个CompletableFuture?如果您控制着提供未来的代码以及它的kotlin,那么使用kotlin协同路由服务可能会有所帮助。收取长时间的计算费用,还是从网络中获取一些东西?它会呼叫其他服务向用户收费。通常2-3秒,这样的函数要么是Kotlin挂起函数,要么接受回调。是否有您正在使用的库?使用@Async和completableFuture。但是仍然不知道在这种情况下如何使用CompletableFuture。您使用的是Java库还是为什么有一个CompletableFuture?如果您控制着提供未来及其kotlin的代码,那么改用kotlin协程可能会有所帮助。让我试试这个,谢谢您,它似乎很管用。但是,requestAll是由其他函数调用的,我得到了挂起函数'requestAll'应该只从一个协程或另一个挂起函数调用。您可以使用CoroutineScope.launch{…}来调用它,让我试试这个。谢谢您,它似乎可以工作。但是,requestAll是由其他函数调用的,我得到了挂起函数'requestAll'应该只从一个协同程序或另一个挂起函数调用。您可以使用协同程序作用域.launch{…}来调用它
var responseMap = mutableMapOf<VendorType, ChargeResponse>()
  requests.forEach {
    val response = when (it.vendorType) {
        VendorType.Type1 -> service.chargeForType1()
        VendorType.Type2 -> service.chargeForType2()

      else -> {
        throw NotImplementedError("${it.vendorType} does not support yet")
      }
    }
    responseMap[it.vendorType] = response
  }
  responseMap