如何与Kotlin协程实现并发?

时间:2019-07-06 00:07:52

标签: android kotlin kotlin-coroutines

我有轮播列表,并在每个轮播上运行,并且基于轮播query我做了fetchAssets()和fetchAssets()是Kotlin暂停的函数,但是问题是每个函数在上一个函数完成时都会被调用我想实现并发性?

 uiScope.launch {
 carousels.mapIndexed { index, carousel ->
when (val assetsResult = assetRepository.fetchAssets(carousel.query)) {
  is Response.Success<List<Asset>> -> {
    if (assetsResult.data.isNotEmpty()) {
      val contentRow = ContentRow(assetsResult.data)
      contentRows.add(contentRow)
      contentRowsmutableData.postValue(contentRows)
    }
  }
  is Response.Failure -> {
  }
}
}
}
override suspend fun fetchAssets(query: String): Response<List<Asset>> {

  return suspendCoroutine { cont ->doHttp(assetsEndpoint, JsonHttpCall("GET"),
        object : JsonReaderResponseHandler() {
          override fun onSuccess(jsonReader: JsonReader) {
              val apiAsset = ApiAssetList(jsonReader)
              cont.resume(Response.Success(apiAsset.items))
          }

          override fun onError(error: Error) {
            cont.resume(Response.Failure("errorMessage"))
          }
        })
  }
}```



1 个答案:

答案 0 :(得分:0)

您必须将暂停功能包装在async块中,然后等待所有异步操作完成:

uiScope.launch {
    val asyncList = carousels.map { carousel ->
        async { assetRepository.fetchAssets(carousel.query) }
    }
    val results = asyncList.awaitAll()
    results.forEach { result ->
        when (result) {
            is Response.Success -> TODO()
            is Response.Failure -> TODO()
        }
    }
}
suspend fun fetchAssets(query: String): Response<List<Asset>>

编辑:如果要在每个UI完成时更新UI,则需要这样更改:

carousels.forEach { carousel ->
    uiScope.launch {
        val result = fetchAssets(carousel.query)
        when (result) {
            is Response.Success -> {
                if (result.data.isNotEmpty()) {
                    val contentRow = ContentRow(result.data)
                    contentRows.add(contentRow)
                    contentRowsmutableData.postValue(contentRows)
                }
            }
            is Response.Failure -> TODO()
        }
    }
}

检查this是否与协程并发。