Skip to content

Instantly share code, notes, and snippets.

@NinoDLC
Created May 6, 2022 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NinoDLC/f54a9fb91bcca60f1a10f11a18c51e26 to your computer and use it in GitHub Desktop.
Save NinoDLC/f54a9fb91bcca60f1a10f11a18c51e26 to your computer and use it in GitHub Desktop.
Query multiple details in parallel with coroutines async / awaitAll()
import kotlinx.coroutines.*
import java.io.IOException
object MultipleDetailsDemo {
@JvmStatic
fun main(args: Array<String>) = runBlocking {
val start = System.currentTimeMillis()
val detailEntities: List<DetailEntity> = try {
val ids = listOf(0, 1, 2)
coroutineScope {
ids.map { id ->
async {
val response = getDetailResponse(id)
if (response.name != null) {
DetailEntity(id, response.name)
} else {
throw IllegalStateException("Name is null !")
}
}
}.awaitAll()
}
} catch (e: Exception) {
e.printStackTrace()
emptyList()
}
println("${System.currentTimeMillis() - start}ms: end of function, entities : $detailEntities")
}
private suspend fun getDetailResponse(id: Int): DetailResponse = when (id) {
-1 -> throw IOException("Socket timeout")
-2 -> DetailResponse(null)
else -> {
delay(200)
DetailResponse("NAME$id")
}
}
data class DetailResponse(
val name: String?
)
data class DetailEntity(
val id: Int,
val name: String
)
}
@NinoDLC
Copy link
Author

NinoDLC commented May 6, 2022

Kotlin Playground here : https://pl.kotl.in/zOtdPSGe4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment