簡體   English   中英

如何與Kotlin協程實現並發?

[英]How to achieve concurrency with 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"))
          }
        })
  }
}```



您必須將您的suspend函數包裝在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,則需要像這樣更改它:

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()
        }
    }
}

檢查與協程的並發性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM