Created
May 6, 2022 07:52
-
-
Save NinoDLC/f54a9fb91bcca60f1a10f11a18c51e26 to your computer and use it in GitHub Desktop.
Query multiple details in parallel with coroutines async / awaitAll()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Kotlin Playground here : https://pl.kotl.in/zOtdPSGe4