[英]Kotlin coroutines runBlocking async
我是協程的新手,並試圖利用它們在更短的時間內多次調用耗時的方法
fun callAPI(idList: Collection<String>): List<String> {
val storedIds = mutableListOf<String>()
runBlocking {
val ids = idList.map { data ->
async {timeConsumingMethod(data)}
}.map { it.await() }
storedIds.addAll(ids)
}
return storedIds
}
我需要對 timeConsumingMethod 的所有調用並行運行,但我不希望 callAPI 在所有 timeConsumingMethods 完成之前返回。
運行這個我看到 timeConsumingMethods 正在同步運行
誰能幫我理解我錯過了什么錯誤?
您需要指定runBlocking
的默認單線程調度程序以外的調度程序,否則無法並行運行。
為了清晰/簡潔,您的代碼也可以重新排列。
fun callAPI(idList: Collection<String>): List<String> = runBlocking(Dispatchers.IO) {
idList.map {
async { timeConsumingMethod(it) }
}.awaitAll()
}
如果您使用的 UI 不想在操作期間凍結,則應考慮將其設為掛起函數並在結果准備好時對其進行響應,而不是使用runBlocking
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.