I have two suspending functions, one that calls an...
# coroutines
r
I have two suspending functions, one that calls an external API multiple times iterating over a list, and then another that fetches data from the database also within an iteration. I need to summarize results from both of these operations and since they're independent from each other, I could run them concurrently. I tried a structure similar to the following (example generated by Gemini):
Copy code
import 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
?
In fact, I just tried the exact code shared in Kotlin Coroutines docs (https://kotlinlang.org/docs/composing-suspending-functions.html#concurrent-using-async) and Sonar is flagging the issue. I'm thinking this is actually a Sonar problem rather than a code bug...