https://kotlinlang.org logo
#coroutines
Title
# coroutines
j

Joshua Hansen

12/14/2023, 4:48 PM
Writing a suspend function, and I'm wondering if there's any meaningful difference between these two options. I think either 1) there isn't, or 2) I've got a gap in my understanding of coroutines. For context:
transformResultRow()
is an expensive operation. Option 1:
Copy code
suspend fun transformData(): List<MyData> {
    val results: List<ResultRow> = queryForData() // queryForData() is a suspend fun querying the db

    return withContext(Dispatchers.Default) {
        results.map { resultRow ->
            async {
                transformResultRow(resultRow) // fun transformResultRow(row: ResultRow): MyData
            }
        }.awaitAll()
    }
}
Option 2: (What's the difference? They both seem to be doing the same thing)
Copy code
suspend fun transformData(): List<MyData> {
    val results: List<ResultRow> = queryForData() // queryForData() is a suspend fun querying the db

    return coroutineScope {
        results.map { resultRow ->
            async(Dispatchers.Default) {
                transformResultRow(resultRow) // fun transformResultRow(row: ResultRow): MyData
            }
        }.awaitAll()
    }
}
It seems that
coroutineScope
is preferred here conventionally.
d

Daniel Pitts

12/14/2023, 4:58 PM
Yeah, the biggest difference is that you're explicitly setting the dispatcher in the first, where the second one will inherit whatever dispatcher was in scope when the transformData() was called.
👍 1
u

uli

12/19/2023, 4:04 PM
Is transformResultRow blocking? Or suspend?