Kotlin协程,如何同步调用并返回结果为地图 [英] Kotlin coroutines, how to async alist of calls and return the result as a map

查看:19
本文介绍了Kotlin协程,如何同步调用并返回结果为地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

希望解决您的问题:

接受您的服务并请求如下:

interface Service {
  suspend fun chargeForType1(): ChargeResponse
  suspend fun chargeForType2(): ChargeResponse
}

data class Request(val vendorType: VendorType)
suspend fun requestAll(requests: List<Request>): Map<VendorType, ChargeResponse> {
  return coroutineScope {
    requests
        .map { request ->
          async {
            request.vendorType to when (request.vendorType) {
              VendorType.Type1 -> service.chargeForType1()
              VendorType.Type2 -> service.chargeForType2()
              else -> throw NotImplementedError("${request.vendorType} does not support yet")
            }
          }
        }
        .awaitAll()
        .toMap()
  }
}

这篇关于Kotlin协程,如何同步调用并返回结果为地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆