Renan Kummer
03/10/2025, 5:28 PMimport kotlinx.coroutines.*
suspend fun getNames(ids: Set<String>): Map<String, String> {
delay(100)
return ids.associateWith { "Name for $it" }
}
suspend fun findBy(id: String): String {
delay(50)
return "Data for $id"
}
data class ProcessSummary(val names: Map<String, String>, val findByResults: Map<String, String>)
suspend fun coordinateProcess(ids: Set<String>, otherIds: Set<String>): ProcessSummary = coroutineScope {
val namesDeferred = async { getNames(ids) }
val findByResultsDeferred = async {
otherIds.associateWith { findBy(it) }
}
val names = namesDeferred.await()
val findByResults = findByResultsDeferred.await()
ProcessSummary(names, findByResults)
}
fun main() = runBlocking {
val ids = setOf("id1", "id2", "id3")
val otherIds = setOf("otherId1", "otherId2")
val summary = coordinateProcess(ids, otherIds)
println("Names: ${summary.names}")
println("FindByResults: ${summary.findByResults}")
}
Sonarqube complains about the async { suspendingFunction() }
structure, though, with "By convention, calls to suspending functions should not block the thread, eliminating the requirement of calling suspending functions on background threads. Any long-running blocking operations should be moved to background threads within the suspending function that performs these operations.".
How else should I run two functions concurrently without using async
?Renan Kummer
03/10/2025, 5:47 PM